summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJérémy Lal <kapouer@melix.org>2016-12-21 07:12:21 -0500
committerJérémy Lal <kapouer@melix.org>2016-12-21 07:12:21 -0500
commitc26036aa8ae4c1167c6b4fe26870800c359a4c96 (patch)
tree1c5106a349fc3ebc9beaf756d252f7cc1aa22dd6
Import node-websocket_1.0.23.orig.tar.gz
[dgit import orig node-websocket_1.0.23.orig.tar.gz]
-rw-r--r--.gitignore9
-rw-r--r--.jshintrc88
-rw-r--r--.npmignore7
-rw-r--r--CHANGELOG.md206
-rw-r--r--LICENSE177
-rw-r--r--Makefile11
-rw-r--r--README.md309
-rw-r--r--binding.gyp18
-rw-r--r--docs/W3CWebSocket.md50
-rw-r--r--docs/WebSocketClient.md112
-rw-r--r--docs/WebSocketConnection.md141
-rw-r--r--docs/WebSocketFrame.md66
-rw-r--r--docs/WebSocketRequest.md113
-rw-r--r--docs/WebSocketServer.md105
-rw-r--r--docs/index.md13
-rw-r--r--example/whiteboard/README10
-rw-r--r--example/whiteboard/index.ejs61
-rw-r--r--example/whiteboard/package.json10
-rw-r--r--example/whiteboard/public/client.css29
-rw-r--r--example/whiteboard/public/client.js189
-rw-r--r--example/whiteboard/whiteboard.js93
-rw-r--r--gulpfile.js14
-rw-r--r--index.js1
-rw-r--r--lib/BufferUtil.fallback.js52
-rw-r--r--lib/BufferUtil.js17
-rw-r--r--lib/Deprecation.js32
-rw-r--r--lib/Validation.fallback.js12
-rw-r--r--lib/Validation.js17
-rw-r--r--lib/W3CWebSocket.js257
-rw-r--r--lib/WebSocketClient.js348
-rw-r--r--lib/WebSocketConnection.js889
-rw-r--r--lib/WebSocketFrame.js279
-rw-r--r--lib/WebSocketRequest.js524
-rw-r--r--lib/WebSocketRouter.js157
-rw-r--r--lib/WebSocketRouterRequest.js54
-rw-r--r--lib/WebSocketServer.js245
-rw-r--r--lib/browser.js36
-rw-r--r--lib/utils.js60
-rw-r--r--lib/version.js1
-rw-r--r--lib/websocket.js11
-rw-r--r--package.json57
-rw-r--r--src/bufferutil.cc121
-rw-r--r--src/validation.cc148
-rw-r--r--test/autobahn/fuzzingclient.json17
-rwxr-xr-xtest/scripts/autobahn-test-client.js135
-rw-r--r--test/scripts/certificate.pem15
-rwxr-xr-xtest/scripts/echo-server.js86
-rwxr-xr-xtest/scripts/fragmentation-test-client.js163
-rw-r--r--test/scripts/fragmentation-test-page.html121
-rwxr-xr-xtest/scripts/fragmentation-test-server.js151
-rwxr-xr-xtest/scripts/libwebsockets-test-client.js101
-rwxr-xr-xtest/scripts/libwebsockets-test-server.js186
-rw-r--r--test/scripts/libwebsockets-test.html253
-rw-r--r--test/scripts/memoryleak-client.js96
-rw-r--r--test/scripts/memoryleak-server.js59
-rw-r--r--test/scripts/privatekey.pem15
-rw-r--r--test/shared/start-echo-server.js56
-rw-r--r--test/shared/test-server.js45
-rw-r--r--test/unit/dropBeforeAccept.js63
-rw-r--r--test/unit/regressions.js31
-rw-r--r--test/unit/request.js105
-rwxr-xr-xtest/unit/w3cwebsocket.js76
-rw-r--r--test/unit/websocketFrame.js32
-rw-r--r--vendor/FastBufferList.js193
64 files changed, 7148 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..10cbcbe
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,9 @@
+node_modules
+.DS_Store
+.lock-*
+build
+build/*
+builderror.log
+npm-debug.log
+test/autobahn/reports*/*
+test/scripts/heapdump/*
diff --git a/.jshintrc b/.jshintrc
new file mode 100644
index 0000000..98d8766
--- /dev/null
+++ b/.jshintrc
@@ -0,0 +1,88 @@
+{
+ // JSHint Default Configuration File (as on JSHint website)
+ // See http://jshint.com/docs/ for more details
+
+ "maxerr" : 50, // {int} Maximum error before stopping
+
+ // Enforcing
+ "bitwise" : false, // true: Prohibit bitwise operators (&, |, ^, etc.)
+ "camelcase" : false, // true: Identifiers must be in camelCase
+ "curly" : true, // true: Require {} for every new block or scope
+ "eqeqeq" : true, // true: Require triple equals (===) for comparison
+ "freeze" : true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc.
+ "forin" : false, // true: Require filtering for..in loops with obj.hasOwnProperty()
+ "immed" : true, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());`
+ "latedef" : "nofunc", // true: Require variables/functions to be defined before being used
+ "newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()`
+ "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee`
+ "noempty" : true, // true: Prohibit use of empty blocks
+ "nonbsp" : true, // true: Prohibit "non-breaking whitespace" characters.
+ "nonew" : true, // true: Prohibit use of constructors for side-effects (without assignment)
+ "plusplus" : false, // true: Prohibit use of `++` & `--`
+ "quotmark" : "single", // Quotation mark consistency:
+ // false : do nothing (default)
+ // true : ensure whatever is used is consistent
+ // "single" : require single quotes
+ // "double" : require double quotes
+ "undef" : true, // true: Require all non-global variables to be declared (prevents global leaks)
+ "unused" : "vars", // vars: Require all defined variables be used, ignore function params
+ "strict" : false, // true: Requires all functions run in ES5 Strict Mode
+ "maxparams" : false, // {int} Max number of formal params allowed per function
+ "maxdepth" : false, // {int} Max depth of nested blocks (within functions)
+ "maxstatements" : false, // {int} Max number statements per function
+ "maxcomplexity" : false, // {int} Max cyclomatic complexity per function
+ "maxlen" : false, // {int} Max number of characters per line
+
+ // Relaxing
+ "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons)
+ "boss" : false, // true: Tolerate assignments where comparisons would be expected
+ "debug" : false, // true: Allow debugger statements e.g. browser breakpoints.
+ "eqnull" : false, // true: Tolerate use of `== null`
+ "es5" : false, // true: Allow ES5 syntax (ex: getters and setters)
+ "esnext" : true, // true: Allow ES.next (ES6) syntax (ex: `const`)
+ "moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features)
+ // (ex: `for each`, multiple try/catch, function expression…)
+ "evil" : false, // true: Tolerate use of `eval` and `new Function()`
+ "expr" : false, // true: Tolerate `ExpressionStatement` as Programs
+ "funcscope" : false, // true: Tolerate defining variables inside control statements
+ "globalstrict" : false, // true: Allow global "use strict" (also enables 'strict')
+ "iterator" : false, // true: Tolerate using the `__iterator__` property
+ "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block
+ "laxbreak" : false, // true: Tolerate possibly unsafe line breakings
+ "laxcomma" : false, // true: Tolerate comma-first style coding
+ "loopfunc" : false, // true: Tolerate functions being defined in loops
+ "multistr" : false, // true: Tolerate multi-line strings
+ "noyield" : false, // true: Tolerate generator functions with no yield statement in them.
+ "notypeof" : false, // true: Tolerate invalid typeof operator values
+ "proto" : false, // true: Tolerate using the `__proto__` property
+ "scripturl" : false, // true: Tolerate script-targeted URLs
+ "shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;`
+ "sub" : true, // true: Tolerate using `[]` notation when it can still be expressed in dot notation
+ "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;`
+ "validthis" : false, // true: Tolerate using this in a non-constructor function
+
+ // Environments
+ "browser" : true, // Web Browser (window, document, etc)
+ "browserify" : true, // Browserify (node.js code in the browser)
+ "couch" : false, // CouchDB
+ "devel" : true, // Development/debugging (alert, confirm, etc)
+ "dojo" : false, // Dojo Toolkit
+ "jasmine" : false, // Jasmine
+ "jquery" : false, // jQuery
+ "mocha" : false, // Mocha
+ "mootools" : false, // MooTools
+ "node" : true, // Node.js
+ "nonstandard" : false, // Widely adopted globals (escape, unescape, etc)
+ "prototypejs" : false, // Prototype and Scriptaculous
+ "qunit" : false, // QUnit
+ "rhino" : false, // Rhino
+ "shelljs" : false, // ShellJS
+ "worker" : false, // Web Workers
+ "wsh" : false, // Windows Scripting Host
+ "yui" : false, // Yahoo User Interface
+
+ // Custom Globals
+ "globals" : { // additional predefined global variables
+ "WebSocket": true
+ }
+}
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 0000000..1ff9305
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,7 @@
+.npmignore
+.gitignore
+
+example/
+build/
+test/
+node_modules/
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..9832b9e
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,206 @@
+Changelog
+=========
+
+Version 1.0.23
+--------------
+*Released 2016-05-18*
+
+* Official support for Node 6.x
+* Updating dependencies. Specifically, updating nan to ^2.3.3
+
+Version 1.0.22
+--------------
+*Released 2015-09-28*
+
+* Updating to work with nan 2.x
+
+Version 1.0.21
+--------------
+*Released 2015-07-22*
+
+* Incrememnted and re-published to work around an aborted npm publish of v1.0.20.
+
+Version 1.0.20
+--------------
+*Released 2015-07-22*
+
+* Added EventTarget to the W3CWebSocket interface (Thanks, [@ibc](https://github.com/ibc)!)
+* Corrected an inaccurate error message. (Thanks, [@lekoaf](https://github.com/lekoaf)!)
+
+Version 1.0.19
+--------------
+*Released 2015-05-28*
+
+* Updated to nan v1.8.x (tested with v1.8.4)
+* Added `"license": "Apache-2.0"` to package.json via [pull request #199](https://github.com/theturtle32/WebSocket-Node/pull/199) by [@pgilad](https://github.com/pgilad). See [npm1k.org](http://npm1k.org/).
+
+
+Version 1.0.18
+--------------
+*Released 2015-03-19*
+
+* Resolves [issue #195](https://github.com/theturtle32/WebSocket-Node/pull/179) - passing number to connection.send() causes crash
+* [Added close code/reason arguments to W3CWebSocket#close()](https://github.com/theturtle32/WebSocket-Node/issues/184)
+
+
+Version 1.0.17
+--------------
+*Released 2015-01-17*
+
+* Resolves [issue #179](https://github.com/theturtle32/WebSocket-Node/pull/179) - Allow toBuffer to work with empty data
+
+
+Version 1.0.16
+--------------
+*Released 2015-01-16*
+
+* Resolves [issue #178](https://github.com/theturtle32/WebSocket-Node/issues/178) - Ping Frames with no data
+
+
+Version 1.0.15
+--------------
+*Released 2015-01-13*
+
+* Resolves [issue #177](https://github.com/theturtle32/WebSocket-Node/issues/177) - WebSocketClient ignores options unless it has a tlsOptions property
+
+
+Version 1.0.14
+--------------
+*Released 2014-12-03*
+
+* Resolves [issue #173](https://github.com/theturtle32/WebSocket-Node/issues/173) - To allow the W3CWebSocket interface to accept an optional non-standard configuration object as its third parameter, which will be ignored when running in a browser context.
+
+
+Version 1.0.13
+--------------
+*Released 2014-11-29*
+
+* Fixes [issue #171](https://github.com/theturtle32/WebSocket-Node/issues/171) - Code to prevent calling req.accept/req.reject multiple times breaks sanity checks in req.accept
+
+
+Version 1.0.12
+--------------
+*Released 2014-11-28*
+
+* Fixes [issue #170](https://github.com/theturtle32/WebSocket-Node/issues/170) - Non-native XOR implementation broken after making JSHint happy
+
+
+Version 1.0.11
+--------------
+*Released 2014-11-25*
+
+* Fixes some undefined behavior surrounding closing WebSocket connections and more reliably handles edge cases.
+* Adds an implementation of the W3C WebSocket API for browsers to facilitate sharing code between client and server via browserify. (Thanks, [@ibc](https://github.com/ibc)!)
+* `WebSocketConnection.prototype.close` now accepts optional `reasonCode` and `description` parameters.
+* Calling `accept` or `reject` more than once on a `WebSocketRequest` will now throw an error. [Issue #149](https://github.com/theturtle32/WebSocket-Node/issues/149)
+* Handling connections dropped by client before accepted by server [Issue #167](https://github.com/theturtle32/WebSocket-Node/issues/167)
+* Integrating Gulp and JSHint (Thanks, [@ibc](https://github.com/ibc)!)
+* Starting to add individual unit tests (using substack's [tape](github.com/substack/tape) and [faucet](github.com/substack/faucet))
+
+
+Version 1.0.10
+--------------
+*Released 2014-10-22*
+
+* Fixed Issue [#146](https://github.com/theturtle32/WebSocket-Node/issues/146) that was causing WebSocketClient to throw errors when instantiated if passed `tlsOptions`.
+
+Version 1.0.9
+-------------
+*Released 2014-10-20*
+
+* Fixing an insidious corner-case bug that prevented `WebSocketConnection` from firing the `close` event in certain cases when there was an error on the underlying `Socket`, leading to connections sticking around forever, stuck erroneously in the `connected` state. These "ghost" connections would cause an error event when trying to write to them.
+* Removed deprecated `websocketVersion` property. Use `webSocketVersion` instead (case difference).
+* Allowing user to specify all properties for `tlsOptions` in WebSocketClient, not just a few whitelisted properties. This keeps us from having to constantly add new config properties for new versions of Node. (Thanks, [jesusprubio](https://github.com/jesusprubio))
+* Removing support for Node 0.4.x and 0.6.x.
+* Adding `fuzzingclient.json` spec file for the Autobahn Test Suite.
+* Now more fairly emitting `message` events from the `WebSocketConnection`. Previously, all buffered frames for a connection would be processed and all `message` events emitted before moving on to processing the next connection with available data. Now We process one frame per connection (most of the time) in a more fair round-robin fashion.
+* Now correctly calling the `EventEmitter` superclass constructor during class instance initialization.
+* `WebSocketClient.prototype.connect` now accepts the empty string (`''`) to mean "no subprotocol requested." Previously either `null` or an empty array (`[]`) was required.
+* Fixing a `TypeError` bug in `WebSocketRouter` (Thanks, [a0000778](https://github.com/a0000778))
+* Fixing a potential race condition when attaching event listeners to the underlying `Socket`. (Thanks [RichardBsolut](https://github.com/RichardBsolut))
+* `WebSocketClient` now accepts an optional options hash to be passed to `(http|https).request`. (Thanks [mildred](https://github.com/mildred) and [aus](https://github.com/aus)) This enables the following new abilities, amongst others:
+ * Use WebSocket-Node from behind HTTP/HTTPS proxy servers using [koichik/node-tunnel](https://github.com/koichik/node-tunnel) or similar.
+ * Specify the local port and local address to bind the outgoing request socket to.
+* Adding option to ignore `X-Forwarded-For` headers when accepting connections from untrusted clients.
+* Adding ability to mount a `WebSocketServer` instance to an arbitrary number of Node http/https servers.
+* Adding browser shim so Browserify won't blow up when trying to package up code that uses WebSocket-Node. The shim is a no-op, it ***does not implement a wrapper*** providing the WebSocket-Node API in the browser.
+* Incorporating upstream enhancements for the native C++ UTF-8 validation and xor masking functions. (Thanks [einaros](https://github.com/einaros) and [kkoopa](https://github.com/kkoopa))
+
+
+Version 1.0.8
+-------------
+*Released 2012-12-26*
+
+* Fixed remaining naming inconsistency of "websocketVersion" as opposed to "webSocketVersion" throughout the code, and added deprecation warnings for use of the old casing throughout.
+* Fixed an issue with our case-insensitive handling of WebSocket subprotocols. Clients that requested a mixed-case subprotocol would end up failing the connection when the server accepted the connection, returning a lower-case version of the subprotocol name. Now we return the subprotocol name in the exact casing that was requested by the client, while still maintaining the case-insensitive verification logic for convenience and practicality.
+* Making sure that any socket-level activity timeout that may have been set on a TCP socket is removed when initializing a connection.
+* Added support for native TCP Keep-Alive instead of using the WebSocket ping/pong packets to serve that function.
+* Fixed cookie parsing to be compliant with RFC 2109
+
+Version 1.0.7
+-------------
+*Released 2012-08-12*
+
+* ***Native modules are now optional!*** If they fail to compile, WebSocket-Node will still work but will not verify that received UTF-8 data is valid, and xor masking/unmasking of payload data for security purposes will not be as efficient as it is performed in JavaScript instead of native code.
+* Reduced Node.JS version requirement back to v0.6.10
+
+Version 1.0.6
+-------------
+*Released 2012-05-22*
+
+* Now requires Node v0.6.13 since that's the first version that I can manage to successfully build the native UTF-8 validator with node-gyp through npm.
+
+Version 1.0.5
+-------------
+*Released 2012-05-21*
+
+* Fixes the issues that users were having building the native UTF-8 validator on Windows platforms. Special Thanks to:
+ * [zerodivisi0n](https://github.com/zerodivisi0n)
+ * [andreasbotsikas](https://github.com/andreasbotsikas)
+* Fixed accidental global variable usage (Thanks, [hakobera](https://github.com/hakobera)!)
+* Added callbacks to the send* methods that provide notification of messages being sent on the wire and any socket errors that may occur when sending a message. (Thanks, [zerodivisi0n](https://github.com/zerodivisi0n)!)
+* Added option to disable logging in the echo-server in the test folder (Thanks, [oberstet](https://github.com/oberstet)!)
+
+
+Version 1.0.4
+-------------
+*Released 2011-12-18*
+
+* Now validates that incoming UTF-8 messages do, in fact, contain valid UTF-8 data. The connection is dropped with prejudice if invalid data is received. This strict behavior conforms to the WebSocket RFC and is verified by the Autobahn Test Suite. This is accomplished in a performant way by using a native C++ Node module created by [einaros](https://github.com/einaros).
+* Updated handling of connection closure to pass more of the Autobahn Test Suite.
+
+Version 1.0.3
+-------------
+*Released 2011-12-18*
+
+* Substantial speed increase (~150% on my machine, depending on the circumstances) due to an optimization in FastBufferList.js that drastically reduces the number of memory alloctions and buffer copying. ([kazuyukitanimura](https://github.com/kazuyukitanimura))
+
+
+Version 1.0.2
+-------------
+*Released 2011-11-28*
+
+* Fixing whiteboard example to work under Node 0.6.x ([theturtle32](https://github.com/theturtle32))
+* Now correctly emitting a `close` event with a 1006 error code if there is a TCP error while writing to the socket during the handshake. ([theturtle32](https://github.com/theturtle32))
+* Catching errors when writing to the TCP socket during the handshake. ([justoneplanet](https://github.com/justoneplanet))
+* No longer outputting console.warn messages when there is an error writing to the TCP socket ([justoneplanet](https://github.com/justoneplanet))
+* Fixing some formatting errors, commas, semicolons, etc. ([kaisellgren](https://github.com/kaisellgren))
+
+
+Version 1.0.1
+-------------
+*Released 2011-11-21*
+
+* Now works with Node 0.6.2 as well as 0.4.12
+* Support TLS in WebSocketClient
+* Added support for setting and reading cookies
+* Added WebSocketServer.prototype.broadcast(data) convenience method
+* Added `resourceURL` property to WebSocketRequest objects. It is a Node URL object with the `resource` and any query string params already parsed.
+* The WebSocket request router no longer includes the entire query string when trying to match the path name of the request.
+* WebSocketRouterRequest objects now include all the properties and events of WebSocketRequest objects.
+* Removed more console.log statements. Please rely on the various events emitted to be notified of error conditions. I decided that it is not a library's place to spew information to the console.
+* Renamed the `websocketVersion` property to `webSocketVersion` throughout the code to fix inconsistent capitalization. `websocketVersion` has been kept for compatibility but is deprecated and may be removed in the future.
+* Now outputting the sanitized version of custom header names rather than the raw value. This prevents invalid HTTP from being put onto the wire if given an illegal header name.
+
+
+I decided it's time to start maintaining a changelog now, starting with version 1.0.1.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..430d42b
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,177 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..39ff645
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,11 @@
+all:
+ node-gyp configure build
+
+clean:
+ node-gyp clean
+
+autobahn:
+ @NODE_PATH=lib node test/autobahn-test-client.js --host=127.0.0.1 --port=9000
+
+autobahn-server:
+ @NODE_PATH=lib node test/echo-server.js
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a813e10
--- /dev/null
+++ b/README.md
@@ -0,0 +1,309 @@
+WebSocket Client & Server Implementation for Node
+=================================================
+
+[![npm version](https://badge.fury.io/js/websocket.svg)](http://badge.fury.io/js/websocket)
+
+[![NPM Downloads](https://img.shields.io/npm/dm/websocket.svg)](https://www.npmjs.com/package/websocket)
+
+[![NPM](https://nodei.co/npm/websocket.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/websocket/)
+
+[![NPM](https://nodei.co/npm-dl/websocket.png?height=3)](https://nodei.co/npm/websocket/)
+
+[ ![Codeship Status for theturtle32/WebSocket-Node](https://codeship.com/projects/70458270-8ee7-0132-7756-0a0cf4fe8e66/status?branch=master)](https://codeship.com/projects/61106)
+
+Overview
+--------
+This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test/scripts" folder.
+
+For a WebSocket client written in ActionScript 3, see my [AS3WebScocket](https://github.com/theturtle32/AS3WebSocket) project.
+
+
+Documentation
+=============
+
+[You can read the full API documentation in the docs folder.](docs/index.md)
+
+
+Changelog
+---------
+
+***Current Version: 1.0.23*** — Released 2016-05-18***
+
+***Version 1.0.23***
+
+* Official support for Node 6.x
+* Updating dependencies. Specifically, updating nan to ^2.3.3
+
+***Version 1.0.22***
+
+* Updating to work with nan 2.x
+
+
+***Version 1.0.21***
+
+* Incrememnted and re-published to work around an aborted npm publish of v1.0.20.
+
+***Version 1.0.20***
+
+* Added EventTarget to the W3CWebSocket interface (Thanks, [@ibc](https://github.com/ibc)!)
+* Corrected an inaccurate error message. (Thanks, [@lekoaf](https://github.com/lekoaf)!)
+
+***Version 1.0.19***
+
+* Updated to nan v1.8.x (tested with v1.8.4)
+* Added `"license": "Apache-2.0"` to package.json via [pull request #199](https://github.com/theturtle32/WebSocket-Node/pull/199) by [@pgilad](https://github.com/pgilad). See [npm1k.org](http://npm1k.org/).
+
+[View the full changelog](CHANGELOG.md)
+
+Browser Support
+---------------
+
+All current browsers are fully supported.
+
+* Firefox 7-9 (Old) (Protocol Version 8)
+* Firefox 10+ (Protocol Version 13)
+* Chrome 14,15 (Old) (Protocol Version 8)
+* Chrome 16+ (Protocol Version 13)
+* Internet Explorer 10+ (Protocol Version 13)
+* Safari 6+ (Protocol Version 13)
+
+***Safari older than 6.0 is not supported since it uses a very old draft of WebSockets***
+
+***If you need to simultaneously support legacy browser versions that had implemented draft-75/draft-76/draft-00, take a look here: https://gist.github.com/1428579***
+
+Benchmarks
+----------
+There are some basic benchmarking sections in the Autobahn test suite. I've put up a [benchmark page](http://theturtle32.github.com/WebSocket-Node/benchmarks/) that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4.
+
+Autobahn Tests
+--------------
+The very complete [Autobahn Test Suite](http://autobahn.ws/testsuite/) is used by most WebSocket implementations to test spec compliance and interoperability.
+
+- [View Server Test Results](http://theturtle32.github.com/WebSocket-Node/test-report/servers/)
+- [View Client Test Results](http://theturtle32.github.com/WebSocket-Node/test-report/clients/)
+
+Notes
+-----
+This library has been used in production on [worlize.com](https://www.worlize.com) since April 2011 and seems to be stable. Your mileage may vary.
+
+**Tested with the following node versions:**
+
+- 6.2.0
+- 5.11.1
+- 4.4.4
+- 0.10.45
+
+It may work in earlier or later versions but I'm not actively testing it outside of the listed versions. YMMV.
+
+Installation
+------------
+
+A few users have reported difficulties building the native extensions without first manually installing node-gyp. If you have trouble building the native extensions, make sure you've got a C++ compiler, and have done `npm install -g node-gyp` first.
+
+Native extensions are optional, however, and WebSocket-Node will work even if the extensions cannot be compiled.
+
+In your project root:
+
+ $ npm install websocket
+
+Then in your code:
+
+```javascript
+var WebSocketServer = require('websocket').server;
+var WebSocketClient = require('websocket').client;
+var WebSocketFrame = require('websocket').frame;
+var WebSocketRouter = require('websocket').router;
+var W3CWebSocket = require('websocket').w3cwebsocket;
+```
+
+Note for Windows Users
+----------------------
+Because there is a small C++ component used for validating UTF-8 data, you will need to install a few other software packages in addition to Node to be able to build this module:
+
+- [Microsoft Visual C++](http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express)
+- [Python 2.7](http://www.python.org/download/) (NOT Python 3.x)
+
+
+Current Features:
+-----------------
+- Licensed under the Apache License, Version 2.0
+- Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake
+- Can handle/aggregate received fragmented messages
+- Can fragment outgoing messages
+- Router to mount multiple applications to various path and protocol combinations
+- TLS supported for outbound connections via WebSocketClient
+- TLS supported for server connections (use https.createServer instead of http.createServer)
+ - Thanks to [pors](https://github.com/pors) for confirming this!
+- Cookie setting and parsing
+- Tunable settings
+ - Max Receivable Frame Size
+ - Max Aggregate ReceivedMessage Size
+ - Whether to fragment outgoing messages
+ - Fragmentation chunk size for outgoing messages
+ - Whether to automatically send ping frames for the purposes of keepalive
+ - Keep-alive ping interval
+ - Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly)
+ - How long to wait after sending a close frame for acknowledgment before closing the socket.
+- [W3C WebSocket API](http://www.w3.org/TR/websockets/) for applications running on both Node and browsers (via the `W3CWebSocket` class).
+
+
+Known Issues/Missing Features:
+------------------------------
+- No API for user-provided protocol extensions.
+
+
+Usage Examples
+==============
+
+Server Example
+--------------
+
+Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.
+
+```javascript
+#!/usr/bin/env node
+var WebSocketServer = require('websocket').server;
+var http = require('http');
+
+var server = http.createServer(function(request, response) {
+ console.log((new Date()) + ' Received request for ' + request.url);
+ response.writeHead(404);
+ response.end();
+});
+server.listen(8080, function() {
+ console.log((new Date()) + ' Server is listening on port 8080');
+});
+
+wsServer = new WebSocketServer({
+ httpServer: server,
+ // You should not use autoAcceptConnections for production
+ // applications, as it defeats all standard cross-origin protection
+ // facilities built into the protocol and the browser. You should
+ // *always* verify the connection's origin and decide whether or not
+ // to accept it.
+ autoAcceptConnections: false
+});
+
+function originIsAllowed(origin) {
+ // put logic here to detect whether the specified origin is allowed.
+ return true;
+}
+
+wsServer.on('request', function(request) {
+ if (!originIsAllowed(request.origin)) {
+ // Make sure we only accept requests from an allowed origin
+ request.reject();
+ console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
+ return;
+ }
+
+ var connection = request.accept('echo-protocol', request.origin);
+ console.log((new Date()) + ' Connection accepted.');
+ connection.on('message', function(message) {
+ if (message.type === 'utf8') {
+ console.log('Received Message: ' + message.utf8Data);
+ connection.sendUTF(message.utf8Data);
+ }
+ else if (message.type === 'binary') {
+ console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
+ connection.sendBytes(message.binaryData);
+ }
+ });
+ connection.on('close', function(reasonCode, description) {
+ console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
+ });
+});
+```
+
+Client Example
+--------------
+
+This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number.
+
+*This code demonstrates a client in Node.js, not in the browser*
+
+```javascript
+#!/usr/bin/env node
+var WebSocketClient = require('websocket').client;
+
+var client = new WebSocketClient();
+
+client.on('connectFailed', function(error) {
+ console.log('Connect Error: ' + error.toString());
+});
+
+client.on('connect', function(connection) {
+ console.log('WebSocket Client Connected');
+ connection.on('error', function(error) {
+ console.log("Connection Error: " + error.toString());
+ });
+ connection.on('close', function() {
+ console.log('echo-protocol Connection Closed');
+ });
+ connection.on('message', function(message) {
+ if (message.type === 'utf8') {
+ console.log("Received: '" + message.utf8Data + "'");
+ }
+ });
+
+ function sendNumber() {
+ if (connection.connected) {
+ var number = Math.round(Math.random() * 0xFFFFFF);
+ connection.sendUTF(number.toString());
+ setTimeout(sendNumber, 1000);
+ }
+ }
+ sendNumber();
+});
+
+client.connect('ws://localhost:8080/', 'echo-protocol');
+```
+
+Client Example using the *W3C WebSocket API*
+--------------------------------------------
+
+Same example as above but using the [W3C WebSocket API](http://www.w3.org/TR/websockets/).
+
+```javascript
+var W3CWebSocket = require('websocket').w3cwebsocket;
+
+var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');
+
+client.onerror = function() {
+ console.log('Connection Error');
+};
+
+client.onopen = function() {
+ console.log('WebSocket Client Connected');
+
+ function sendNumber() {
+ if (client.readyState === client.OPEN) {
+ var number = Math.round(Math.random() * 0xFFFFFF);
+ client.send(number.toString());
+ setTimeout(sendNumber, 1000);
+ }
+ }
+ sendNumber();
+};
+
+client.onclose = function() {
+ console.log('echo-protocol Client Closed');
+};
+
+client.onmessage = function(e) {
+ if (typeof e.data === 'string') {
+ console.log("Received: '" + e.data + "'");
+ }
+};
+```
+
+Request Router Example
+----------------------
+
+For an example of using the request router, see `libwebsockets-test-server.js` in the `test` folder.
+
+
+Resources
+---------
+
+A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. [WebSockets: The Real-Time Web, Delivered](http://www.scribd.com/doc/60898569/WebSockets-The-Real-Time-Web-Delivered)
diff --git a/binding.gyp b/binding.gyp
new file mode 100644
index 0000000..77b2ed5
--- /dev/null
+++ b/binding.gyp
@@ -0,0 +1,18 @@
+{
+ 'targets': [
+ {
+ 'target_name': 'validation',
+ 'include_dirs': ["<!(node -e \"require('nan')\")"],
+ 'cflags!': [ '-O3' ],
+ 'cflags': [ '-O2' ],
+ 'sources': [ 'src/validation.cc' ]
+ },
+ {
+ 'target_name': 'bufferutil',
+ 'include_dirs': ["<!(node -e \"require('nan')\")"],
+ 'cflags!': [ '-O3' ],
+ 'cflags': [ '-O2' ],
+ 'sources': [ 'src/bufferutil.cc' ]
+ }
+ ]
+}
diff --git a/docs/W3CWebSocket.md b/docs/W3CWebSocket.md
new file mode 100644
index 0000000..3bf505b
--- /dev/null
+++ b/docs/W3CWebSocket.md
@@ -0,0 +1,50 @@
+W3CWebSocket
+============
+
+* [Constructor](#constructor)
+* [Limitations](#limitations)
+
+`var W3CWebSocket = require('websocket').w3cwebsocket`
+
+Implementation of the [W3C WebSocket API](http://www.w3.org/TR/websockets/) for browsers.
+
+The exposed class lets the developer use the browser *W3C WebSocket API* in Node:
+
+```javascript
+var WS = require('websocket').w3cwebsocket;
+
+WS === window.WebSocket
+// => true when in the browser
+
+var ws = new WS('ws://example.com/resource', 'foo', 'http://example.com');
+// - In Node it creates an instance of websocket.W3CWebSocket.
+// - In the browser it creates an instance of window.WebSocket (third parameter
+// is ignored by the native WebSocket constructor).
+
+ws.onopen = function() { console.log('ws open'); };
+// etc.
+```
+
+
+Constructor
+-----------
+
+```javascript
+new W3CWebSocket(requestUrl, requestedProtocols, [[[[origin], headers], requestOptions], clientConfig])
+```
+
+**clientConfig** is the parameter of the [WebSocketClient](./WebSocketClient.md) constructor.
+
+**requestUrl**, **requestedProtocols**, **origin**, **headers** and **requestOptions** are parameters to be used in the `connect()` method of [WebSocketClient](./WebSocketClient.md).
+
+This constructor API makes it possible to use the W3C API and "browserify" the Node application into a valid browser library.
+
+When running in a browser (for example by using [browserify](http://browserify.org/)) the browser's native `WebSocket` implementation is used, and thus just the first and second arguments (`requestUrl` and `requestedProtocols`) are used (those allowed by the *W3C WebSocket API*).
+
+
+Limitations
+-----------
+
+* `bufferedAmount` attribute is always 0.
+* `binaryType` is "arraybuffer" by default given that "blob" is not supported (Node does not implement the `Blob` class).
+* `send()` method allows arguments of type `DOMString`, `ArrayBuffer`, `ArrayBufferView` (`Int8Array`, etc) or Node `Buffer`, but does not allow `Blob`.
diff --git a/docs/WebSocketClient.md b/docs/WebSocketClient.md
new file mode 100644
index 0000000..c295343
--- /dev/null
+++ b/docs/WebSocketClient.md
@@ -0,0 +1,112 @@
+WebSocketClient
+===============
+
+* [Constructor](#constructor)
+* [Config Options](#client-config-options)
+* [Methods](#methods)
+* [Events](#events)
+* **Examples**
+ * [Connect using a Proxy Server](#connect-using-a-proxy-server)
+
+`var WebSocketClient = require('websocket').client`
+
+This object allows you to make client connections to a WebSocket server.
+
+Constructor
+-----------
+```javascript
+new WebSocketClient([clientConfig]);
+```
+
+Client Config Options
+---------------------
+**webSocketVersion** - uint - *Default: 13*
+Which version of the WebSocket protocol to use when making the connection. Currently supported values are 8 and 13.
+This option will be removed once the protocol is finalized by the IETF It is only available to ease the transition through the intermediate draft protocol versions. The only thing this affects the name of the Origin header.
+
+**maxReceivedFrameSize** - uint - *Default: 1MiB*
+The maximum allowed received frame size in bytes. Single frame messages will also be limited to this maximum.
+
+**maxReceivedMessageSize** - uint - *Default: 8MiB*
+The maximum allowed aggregate message size (for fragmented messages) in bytes.
+
+**fragmentOutgoingMessages** - Boolean - *Default: true*
+Whether or not to fragment outgoing messages. If true, messages will be automatically fragmented into chunks of up to `fragmentationThreshold` bytes.
+
+**fragmentationThreshold** - uint - *Default: 16KiB*
+The maximum size of a frame in bytes before it is automatically fragmented.
+
+**assembleFragments** - boolean - *Default: true*
+If true, fragmented messages will be automatically assembled and the full message will be emitted via a `message` event. If false, each frame will be emitted on the WebSocketConnection object via a `frame` event and the application will be responsible for aggregating multiple fragmented frames. Single-frame messages will emit a `message` event in addition to the `frame` event. Most users will want to leave this set to `true`.
+
+**closeTimeout** - uint - *Default: 5000*
+The number of milliseconds to wait after sending a close frame for an acknowledgement to come back before giving up and just closing the socket.
+
+**tlsOptions** - object - *Default: {}*
+Options to pass to `https.request` if connecting via TLS. See [Node's HTTPS documentation](http://nodejs.org/api/https.html#https_https_request_options_callback)
+
+
+Methods
+-------
+###connect(requestUrl, requestedProtocols, [[[origin], headers], requestOptions])
+
+Will establish a connection to the given `requestUrl`. `requestedProtocols` indicates a list of multiple subprotocols supported by the client. The remote server will select the best subprotocol that it supports and send that back when establishing the connection. `origin` is an optional field that can be used in user-agent scenarios to identify the page containing any scripting content that caused the connection to be requested. (This seems unlikely in node.. probably should leave it null most of the time.) `requestUrl` should be a standard websocket url, such as:
+`ws://www.mygreatapp.com:1234/websocketapp/`
+
+`headers` should be either `null` or an object specifying additional arbitrary HTTP request headers to send along with the request. This may be used to pass things like access tokens, etc. so that the server can verify authentication/authorization before deciding to accept and open the full WebSocket connection.
+
+`requestOptions` should be either `null` or an object specifying additional configuration options to be passed to `http.request` or `https.request`. This can be used to pass a custom `agent` to enable `WebSocketClient` usage from behind an HTTP or HTTPS proxy server using [koichik/node-tunnel](https://github.com/koichik/node-tunnel) or similar.
+
+`origin` must be specified if you want to pass `headers`, and both `origin` and `headers` must be specified if you want to pass `requestOptions`. The `origin` and `headers` parameters may be passed as `null`.
+
+###abort()
+
+Will cancel an in-progress connection request before either the `connect` event or the `connectFailed` event has been emitted. If the `connect` or `connectFailed` event has already been emitted, calling `abort()` will do nothing.
+
+
+Events
+------
+###connect
+`function(webSocketConnection)`
+
+Emitted upon successfully negotiating the WebSocket handshake with the remote server. `webSocketConnection` is an instance of `WebSocketConnection` that can be used to send and receive messages with the remote server.
+
+###connectFailed
+`function(errorDescription)`
+
+Emitted when there is an error connecting to the remote host or the handshake response sent by the server is invalid.
+
+###httpResponse
+`function(response, webSocketClient)`
+
+Emitted when the server replies with anything other then "101 Switching Protocols". Provides an opportunity to handle redirects for example. The `response` parameter is an instance of the [http.IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage) class. This is not suitable for handling receiving of large response bodies, as the underlying socket will be immediately closed by WebSocket-Node as soon as all handlers for this event are executed.
+
+Normally, if the remote server sends an HTTP response with a response code other than 101, the `WebSocketClient` will automatically emit the `connectFailed` event with a description of what was received from the remote server. However, if there are one or more listeners attached to the `httpResponse` event, then the `connectFailed` event will not be emitted for non-101 responses received. `connectFailed` will still be emitted for non-HTTP errors, such as when the remote server is unreachable or not accepting TCP connections.
+
+
+Examples
+========
+
+Connect using a Proxy Server
+----------------------------
+
+Using [koichik/node-tunnel](https://github.com/koichik/node-tunnel):
+
+```javascript
+var WebSocketClient = require('websocket').client;
+var client = new WebSocketClient();
+var tunnel = require('tunnel');
+
+var tunnelingAgent = tunnel.httpOverHttp({
+ proxy: {
+ host: 'proxy.host.com',
+ port: 8080
+ }
+});
+
+var requestOptions = {
+ agent: tunnelingAgent
+};
+
+client.connect('ws://echo.websocket.org/', null, null, null, requestOptions);
+```
diff --git a/docs/WebSocketConnection.md b/docs/WebSocketConnection.md
new file mode 100644
index 0000000..8a5bfe8
--- /dev/null
+++ b/docs/WebSocketConnection.md
@@ -0,0 +1,141 @@
+WebSocketConnection
+===================
+
+* [Constructor](#constructor)
+* [Properties](#properties)
+* [Methods](#methods)
+* [Events](#events)
+
+This object provides the interface through which you can communicate with connected peers. It is used in both WebSocketServer and WebSocketClient situations.
+
+Constructor
+-----------
+This object is created internally by `WebSocketRequest`.
+
+Properties
+----------
+
+###closeDescription
+
+After the connection is closed, contains a textual description of the reason for the connection closure, or `null` if the connection is still open.
+
+###closeReasonCode
+
+After the connection is closed, contains the numeric close reason status code, or `-1` if the connection is still open.
+
+###socket
+
+The underlying net.Socket instance for the connection.
+
+###protocol
+
+The subprotocol that was chosen to be spoken on this connection. This field will have been converted to lower case.
+
+###extensions
+
+An array of extensions that were negotiated for this connection. Currently unused, will always be an empty array.
+
+###remoteAddress
+
+The IP address of the remote peer as a string. In the case of a server, the `X-Forwarded-For` header will be respected and preferred for the purposes of populating this field. If you need to get to the actual remote IP address, `webSocketConnection.socket.remoteAddress` will provide it.
+
+###webSocketVersion
+
+A number indicating the version of the WebSocket protocol being spoken on this connection.
+
+###connected
+
+A boolean value indicating whether or not the connection is still connected. *Read-only*
+
+Methods
+-------
+###close([reasonCode], [description])
+
+Will gracefully close the connection. A close frame will be sent to the remote peer with the provided `reasonCode` and `description` indicating that we wish to close the connection, and we will then wait for up to `config.closeTimeout` milliseconds for an acknowledgment from the remote peer before terminating the underlying socket connection. The `closeTimeout` is passed as part of the `serverOptions` or `clientOptions` hashes to either the `WebSocketServer` or `WebSocketClient` constructors. Most of the time, you should call `close()` without arguments to initiate a normal connection closure. If you specify a `reasonCode` that is defined as one of the standard codes in the WebSocket protocol specification and do not provide a `description`, the default description for the given code will be used. If you would prefer not to send a description at all, pass an empty string `''`as the description parameter.
+
+###drop([reasonCode], [description])
+
+Will send a close frame to the remote peer with the provided `reasonCode` and `description` and will immediately close the socket without waiting for a response. This should generally be used only in error conditions. The default `reasonCode` is 1002 (Protocol Error). Close reasons defined by the WebSocket protocol draft include:
+
+```javascript
+WebSocketConnection.CLOSE_REASON_NORMAL = 1000;
+WebSocketConnection.CLOSE_REASON_GOING_AWAY = 1001;
+WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR = 1002;
+WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT = 1003;
+WebSocketConnection.CLOSE_REASON_RESERVED = 1004; // Reserved value. Undefined meaning.
+WebSocketConnection.CLOSE_REASON_NOT_PROVIDED = 1005; // Not to be used on the wire
+WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006; // Not to be used on the wire
+WebSocketConnection.CLOSE_REASON_INVALID_DATA = 1007;
+WebSocketConnection.CLOSE_REASON_POLICY_VIOLATION = 1008;
+WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG = 1009;
+WebSocketConnection.CLOSE_REASON_EXTENSION_REQUIRED = 1010;
+```
+###sendUTF(string)
+
+Immediately sends the specified string as a UTF-8 WebSocket message to the remote peer. If `config.fragmentOutgoingMessages` is `true` the message may be sent as multiple fragments if it exceeds `config.fragmentationThreshold` bytes. Any object that implements the `toString()` method may be passed to `sendUTF()`
+
+###sendBytes(buffer)
+
+Immediately sends the specified Node `Buffer` object as a Binary WebSocket message to the remote peer. If `config.fragmentOutgoingMessages` is `true` the message may be sent as multiple fragments if it exceeds `config.fragmentationThreshold` bytes.
+
+###send(data)
+
+A convenience function that will auto-detect the data type and send the appropriate WebSocket message accordingly. Immediately sends the specified data as either a UTF-8 or Binary message. If `data` is a Node Buffer, a binary message will be sent. Otherwise, the object provided must implement the `toString()` method, and the result of calling `toString()` on the `data` object will be sent as a UTF-8 message.
+
+###ping(data)
+
+Sends a ping frame to the remote peer. `data` can be a Node `Buffer` or any object that implements `toString()`, such as a `string` or `number`. Ping frames must not exceed 125 bytes in length.
+
+###pong(buffer)
+
+Sends a pong frame to the remote peer. Pong frames may be sent unsolicited and such pong frames will trigger no action on the receiving peer. Pong frames sent in response to a ping frame must mirror the payload data of the ping frame exactly. The `WebSocketConnection` object handles this internally for you, so there should be no need to use this method to respond to pings unless you explicitly cancel() this internal behavior (see ping event below). Pong frames must not exceed 125 bytes in length.
+
+###sendFrame(webSocketFrame)
+
+Serializes a `WebSocketFrame` object into binary data and immediately sends it to the remote peer. This is an advanced function, requiring you to manually compose your own `WebSocketFrame`. You should probably use `sendUTF` or `sendBytes` instead.
+
+Events
+------
+###message
+`function(message)`
+
+Emitted whenever a complete single-frame message is received, or if `config.assembleFragments` is `true` (the default), it will also be emitted with a complete message assembled from multiple fragmented frames. This is the primary event to listen for to receive messages from the remote peer. The `message` object looks like the following:
+
+```javascript
+// For Text Frames:
+{
+ type: "utf8",
+ utf8Data: "A string containing the received message."
+}
+
+// For Binary Frames:
+{
+ type: "binary",
+ binaryData: binaryDataBuffer // a Buffer object containing the binary message payload
+}
+```
+
+###frame
+`function(webSocketFrame)`
+
+This event is emitted only if `config.assembleFragments` is `false` (default is `true`). This allows you to handle individual fragments as they are received without waiting on `WebSocketConnection` to buffer them into a single `message` event for you. This may be desirable if you are working with streaming data, as it is possible to send fragments continually without ever stopping. `webSocketFrame` is an instance of `WebSocketFrame` which has properties that represent all the individual fields in WebSocket's binary framing protocol.
+
+###close
+`function(reasonCode, description)`
+
+This event is emitted when the connection has been fully closed and the socket is no longer connected. `reasonCode` is the numeric reason code for the connection closure. `description` is a textual explanation for the connection closure, if available.
+
+###error
+`function(error)`
+
+This event is emitted when there has been a socket error. If this occurs, a `close` event will also be emitted.
+
+###ping
+`function(cancel, data)`
+
+This event is emitted when the connection receives a `ping` from the peer. `cancel` is a function taking no arguments that when called prevents the WebSocketConnection object from automatically replying with a `pong`. `data` is the binary payload contained in the ping frame.
+
+###pong
+`function(data)`
+
+This event is emitted when the connection receives a `pong` from the peer. `data` is the binary data contained in the pong frame.
diff --git a/docs/WebSocketFrame.md b/docs/WebSocketFrame.md
new file mode 100644
index 0000000..e3160d3
--- /dev/null
+++ b/docs/WebSocketFrame.md
@@ -0,0 +1,66 @@
+WebSocketFrame
+==============
+
+* [Constructor](#constructor)
+* [Properties](#properties)
+
+`var WebSocketFrame = require('websocket').frame`
+
+This object represents the low level individual frame and is used to drive how the bytes are serialized onto the wire.
+
+Constructor
+-----------
+```javascript
+new WebSocketFrame();
+```
+
+Properties
+----------
+
+###fin
+*Boolean*
+
+Indicates that this is either the only frame in a message, or the last frame in a fragmentation sequence.
+
+###rsv1
+*Boolean*
+
+Represents the RSV1 field in the framing, which is currently not used. Setting this to true will result in a Protocol Error on the receiving peer.
+
+###rsv2
+*Boolean*
+
+Represents the RSV2 field in the framing, which is currently not used. Setting this to true will result in a Protocol Error on the receiving peer.
+
+###rsv3
+*Boolean*
+
+Represents the RSV3 field in the framing, which is currently not used. Setting this to true will result in a Protocol Error on the receiving peer.
+
+###mask
+*uint*
+
+Whether or not this frame is (or should be) masked. For outgoing frames, when connected as a client, this flag is automatically forced to `true` by WebSocketConnection. Outgoing frames sent from the server-side of a connection are not masked.
+
+###opcode
+*uint*
+
+Identifies which kind of frame this is. List of Opcodes:
+
+ Hex - Dec - Description
+ 0x00 - 0 - Continuation
+ 0x01 - 1 - Text Frame
+ 0x02 - 2 - Binary Frame
+ 0x08 - 8 - Close Frame
+ 0x09 - 9 - Ping Frame
+ 0x0A - 10 - Pong Frame
+
+###length
+*Read-only, uint*
+
+Identifies the length of the payload data on a received frame. When sending a frame, the length will be automatically calculated from the `binaryPayload` object.
+
+###binaryPayload
+*Buffer object*
+
+The binary payload data. **NOTE**: Even text frames are sent with a Buffer providing the binary payload data. When sending a UTF-8 Text Frame, you must serialize your string into a Buffer object before constructing your frame, and when receiving a UTF-8 Text Frame, you must deserialize the string from the provided Buffer object. Do not read UTF-8 data from fragmented Text Frames, as it may have fragmented the data in the middle of a UTF-8 encoded character. You should buffer all fragments of a text message before attempting to decode the UTF-8 data.
diff --git a/docs/WebSocketRequest.md b/docs/WebSocketRequest.md
new file mode 100644
index 0000000..11e6d60
--- /dev/null
+++ b/docs/WebSocketRequest.md
@@ -0,0 +1,113 @@
+WebSocketRequest
+================
+
+* [Constructor](#constructor)
+* [Properties](#properties)
+* [Methods](#methods)
+* [Events](#events)
+
+This object represents a client requesting to connect to the server, and allows you to accept or reject the connection based on whatever criteria you decide.
+
+Constructor
+-----------
+This object is created internally by `WebSocketServer`.
+
+However if you need to integrate WebSocket support without mounting an instance of `WebSocketServer` to your http server directly, you can handle the `upgrade` event yourself and pass the appropriate parameters to the `WebSocketRequest` constructor. **NOTE:** You *must* pass a complete set of config options to the constructor. See the section *'Server Config Options'* above. The only option that isn't required in this context is `httpServer`.
+
+```javascript
+new WebSocketRequest(socket, httpRequest, config);
+```
+
+The constructor won't immediately parse and validate the handshake from the client, so you need to call `readHandshake()`, which will `throw` an error if the handshake from the client is invalid or if an error is encountered, so it must always be wrapped in a try/catch block.
+
+Properties
+----------
+###httpRequest
+
+A reference to the original Node HTTP request object. This may be useful in combination with some other Node-based web server, such as Express, for accessing cookies or session data.
+
+
+###host
+
+A string containing the contents of the `Host` header passed by the client. This will include the port number if a non-standard port is used.
+
+Examples:
+```
+www.example.com
+www.example.com:8080
+127.0.0.1:3000
+```
+
+###resource
+
+A string containing the path that was requested by the client.
+
+###resourceURL
+
+A Node URL object containing the parsed `resource`, including the query string parameters.
+
+###remoteAddress
+
+The remote client's IP Address as a string. If an `X-Forwarded-For` header is present, the value will be taken from that header to facilitate WebSocket servers that live behind a reverse-proxy.
+
+###websocketVersion
+
+**Deprecated, renamed to webSocketVersion**
+
+###webSocketVersion
+
+A number indicating the version of the WebSocket protocol requested by the client.
+
+###origin
+
+If the client is a web browser, `origin` will be a string containing the URL of the page containing the script that opened the connection. If the client is **not** a web browser, `origin` may be `null` or "*".
+
+###requestedExtensions
+
+An array containing a list of extensions requested by the client. This is not currently used for anything. **Example:**
+
+```javascript
+[
+ {
+ name: "simple-extension";
+ },
+ {
+ name: "my-great-compression-extension",
+ params: [
+ {
+ name: "compressionLevel",
+ value: "10";
+ }
+ ]
+ }
+]
+```
+
+###requestedProtocols
+
+An array containing a list of strings that indicate the subprotocols the client would like to speak. The server should select the best one that it can support from the list and pass it to the accept() function when accepting the connection. Note that all the strings in the `requestedProtocols` array will have been converted to lower case, so that acceptance of a subprotocol can be case-insensitive.
+
+Methods
+-------
+
+###accept(acceptedProtocol, allowedOrigin)
+*Returns: WebSocketConnection instance*
+
+After inspecting the WebSocketRequest's properties, call this function on the request object to accept the connection. If you don't have a particular subprotocol you wish to speak, you may pass `null` for the `acceptedProtocol` parameter. Note that the `acceptedProtocol` parameter is *case-insensitive*, and you must either pass a value that was originally requested by the client or `null`. For browser clients (in which the `origin` property would be non-null) you must pass that user's origin as the `allowedOrigin` parameter to confirm that you wish to accept connections from the given origin. The return value contains the established `WebSocketConnection` instance that can be used to communicate with the connected client.
+
+###reject([httpStatus], [reason])
+
+If you decide to reject the connection, you must call `reject`. You may optionally pass in an HTTP Status code (such as 404) and a textual description that will be sent to the client in the form of an "X-WebSocket-Reject-Reason" header. The connection will then be closed.
+
+Events
+------
+
+###requestAccepted
+`function(webSocketConnection)`
+
+Emitted by the WebSocketRequest object when the `accept` method has been called and the connection has been established. `webSocketConnection` is the established `WebSocketConnection` instance that can be used to communicate with the connected client.
+
+###requestRejected
+`function()`
+
+Emitted by the WebSocketRequest object when the `reject` method has been called and the connection has been terminated.
diff --git a/docs/WebSocketServer.md b/docs/WebSocketServer.md
new file mode 100644
index 0000000..20154eb
--- /dev/null
+++ b/docs/WebSocketServer.md
@@ -0,0 +1,105 @@
+WebSocketServer
+===============
+
+* [Constructor](#constructor)
+* [Config Options](#server-config-options)
+* [Properties](#properties)
+* [Methods](#methods)
+* [Events](#events)
+
+`var WebSocketServer = require('websocket').server`
+
+Constructor
+-----------
+
+```javascript
+new WebSocketServer([serverConfig]);
+```
+
+Methods
+-------
+
+###mount(serverConfig)
+
+`mount` will attach the WebSocketServer instance to a Node http.Server instance. `serverConfig` is required, and is an object with configuration values. For those values, see **Server Config Options** below. If you passed `serverConfig` to the constructor, this function will automatically be invoked.
+
+###unmount()
+
+`unmount` will detach the WebSocketServer instance from the Node http.Server instance. All existing connections are left alone and will not be affected, but no new WebSocket connections will be accepted.
+
+###closeAllConnections()
+
+Will gracefully close all open WebSocket connections.
+
+###shutDown()
+
+Gracefully closes all open WebSocket connections and unmounts the server from the Node http.Server instance.
+
+Server Config Options
+---------------------
+**httpServer** - (http.Server instance) **Required**.
+The Node http or https server instance(s) to attach to. You can pass a single instance directly, or pass an array of instances to attach to multiple http/https servers. Passing an array is particularly useful when you want to accept encrypted and unencrypted WebSocket connections on both ws:// and wss:// protocols using the same WebSocketServer instance.
+
+**maxReceivedFrameSize** - uint - *Default: 64KiB*
+The maximum allowed received frame size in bytes. Single frame messages will also be limited to this maximum.
+
+**maxReceivedMessageSize** - uint - *Default: 1MiB*
+The maximum allowed aggregate message size (for fragmented messages) in bytes.
+
+**fragmentOutgoingMessages** - Boolean - *Default: true*
+Whether or not to fragment outgoing messages. If true, messages will be automatically fragmented into chunks of up to `fragmentationThreshold` bytes.
+
+**fragmentationThreshold** - uint - *Default: 16KiB*
+The maximum size of a frame in bytes before it is automatically fragmented.
+
+**keepalive** - boolean - *Default: true*
+If true, the server will automatically send a ping to all clients every `keepaliveInterval` milliseconds. Each client has an independent keepalive timer, which is reset when any data is received from that client.
+
+**keepaliveInterval** - uint - *Default: 20000*
+The interval in milliseconds to send keepalive pings to connected clients.
+
+**dropConnectionOnKeepaliveTimeout** - boolean - *Default: true*
+If true, the server will consider any connection that has not received any data within the amount of time specified by `keepaliveGracePeriod` after a keepalive ping has been sent. Ignored if `keepalive` is false.
+
+**keepaliveGracePeriod** - uint - *Default: 10000*
+The amount of time to wait after sending a keepalive ping before closing the connection if the connected peer does not respond. Ignored if `keepalive` or `dropConnectionOnKeepaliveTimeout` are false. The grace period timer is reset when any data is received from the client.
+
+**assembleFragments** - boolean - *Default: true*
+If true, fragmented messages will be automatically assembled and the full message will be emitted via a `message` event. If false, each frame will be emitted on the WebSocketConnection object via a `frame` event and the application will be responsible for aggregating multiple fragmented frames. Single-frame messages will emit a `message` event in addition to the `frame` event. Most users will want to leave this set to `true`.
+
+**autoAcceptConnections** - boolean - *Default: false*
+If this is true, websocket connections will be accepted regardless of the path and protocol specified by the client. The protocol accepted will be the first that was requested by the client. Clients from any origin will be accepted. This should only be used in the simplest of cases. You should probably leave this set to `false`; and inspect the request object to make sure it's acceptable before accepting it.
+
+**closeTimeout** - uint - *Default: 5000*
+The number of milliseconds to wait after sending a close frame for an acknowledgement to come back before giving up and just closing the socket.
+
+**disableNagleAlgorithm** - boolean - *Default: true*
+The Nagle Algorithm makes more efficient use of network resources by introducing a small delay before sending small packets so that multiple messages can be batched together before going onto the wire. This however comes at the cost of latency, so the default is to disable it. If you don't need low latency and are streaming lots of small messages, you can change this to 'false';
+
+**ignoreXForwardedFor** - Boolean - *Default: false*
+Whether or not the `X-Forwarded-For` header should be respected.
+It's important to set this to 'true' when accepting connections
+from untrusted clients, as a malicious client could spoof its
+IP address by simply setting this header. It's meant to be added
+by a trusted proxy or other intermediary within your own
+infrastructure.
+More info: [X-Forwarded-For on Wikipedia](http://en.wikipedia.org/wiki/X-Forwarded-For)
+
+Events
+------
+There are three events emitted by a WebSocketServer instance that allow you to handle incoming requests, establish connections, and detect when a connection has been closed.
+
+###request
+`function(webSocketRequest)`
+
+If `autoAcceptConnections` is set to `false`, a `request` event will be emitted by the server whenever a new WebSocket request is made. You should inspect the requested protocols and the user's origin to verify the connection, and then accept or reject it by calling webSocketRequest.accept('chosen-protocol', 'accepted-origin') or webSocketRequest.reject()
+
+###connect
+`function(webSocketConnection)`
+
+Emitted whenever a new WebSocket connection is accepted.
+
+###close
+`function(webSocketConnection, closeReason, description)`
+
+Whenever a connection is closed for any reason, the WebSocketServer instance will emit a `close` event, passing a reference to the WebSocketConnection instance that was closed. `closeReason` is the numeric reason status code for the connection closure, and `description` is a textual description of the close reason, if available.
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..d42a250
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,13 @@
+WebSocket-Node Documentation
+============================
+
+WebSocket-Node includes both client and server functionality, available through WebSocketClient and WebSocketServer respectively. Once a connection is established, the API for sending and receiving messages is identical whether you're acting as a client or server.
+
+Click on one of the classes below to view its API documentation.
+
+* [WebSocketClient](./WebSocketClient.md)
+* [WebSocketConnection](./WebSocketConnection.md)
+* [WebSocketFrame](./WebSocketFrame.md)
+* [WebSocketRequest](./WebSocketRequest.md)
+* [WebSocketServer](./WebSocketServer.md)
+* [W3CWebSocket](./W3CWebSocket.md)
diff --git a/example/whiteboard/README b/example/whiteboard/README
new file mode 100644
index 0000000..17e4130
--- /dev/null
+++ b/example/whiteboard/README
@@ -0,0 +1,10 @@
+To run the whiteboard example, make sure to run..
+
+npm install "express@2.3.11" "ejs@0.4.3"
+
+..from within the 'whiteboard' folder, then fire up the example server with..
+
+node ./whiteboard.js
+
+..and navigate to http://localhost:8080 from a browser supporting draft-09
+of the WebSockets specification.
diff --git a/example/whiteboard/index.ejs b/example/whiteboard/index.ejs
new file mode 100644
index 0000000..1d72b82
--- /dev/null
+++ b/example/whiteboard/index.ejs
@@ -0,0 +1,61 @@
+<!DOCTYPE html>
+<html>
+<!--
+ Copyright 2010-2015 Brian McKelvey.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<head>
+ <meta charset="utf-8">
+ <title>WebSocket Whiteboard Example</title>
+ <script src="/client.js" type="text/javascript" charset="utf-8"></script>
+ <link rel="stylesheet" href="/client.css">
+</head>
+<body>
+ <h1>Shared Whiteboard Example</h1>
+
+ <p>As of the time of this writing, this example requires at least
+ <a href="http://www.mozilla.com/firefox/channel/">Firefox 7 beta</a> or
+ <a href="http://www.google.com/landing/chrome/beta/">Chrome 14 beta</a>.</p>
+
+ <canvas id="whiteboardCanvas" width="800" height="450"></canvas>
+
+ <br>
+ <button onclick="setColor(200,0,0)"
+ style="color: #FFF; background-color: rgb(200,0,0)">Red</button>
+
+ <button onclick="setColor(0,128,0)"
+ style="color: #FFF; background-color: rgb(0,128,0)">Green</button>
+
+ <button onclick="setColor(0,0,255)"
+ style="color: #FFF; background-color: rgb(0,0,255)">Blue</button>
+
+ <button onclick="setColor(0,0,0)"
+ style="color: #FFF; background-color: rgb(0,0,0)">Black</button>
+
+ <button onclick="erase()">Erase Whiteboard</button>
+
+ <script>
+ var client = new Whiteboard('whiteboardCanvas');
+ client.connect();
+
+ function erase() {
+ client.sendClear();
+ }
+
+ function setColor(r,g,b) {
+ client.setColor(r,g,b);
+ }
+ </script>
+</body>
+</html>
diff --git a/example/whiteboard/package.json b/example/whiteboard/package.json
new file mode 100644
index 0000000..7899ddc
--- /dev/null
+++ b/example/whiteboard/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "websocket-whiteboard-example",
+ "description": "Whiteboard example for websocket-node.",
+ "author": "Brian McKelvey <brian@worlize.com> (https://www.worlize.com/)",
+ "version": "1.0.0",
+ "dependencies": {
+ "express": "~2",
+ "ejs": "*"
+ }
+} \ No newline at end of file
diff --git a/example/whiteboard/public/client.css b/example/whiteboard/public/client.css
new file mode 100644
index 0000000..358f832
--- /dev/null
+++ b/example/whiteboard/public/client.css
@@ -0,0 +1,29 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+h1 {
+ font-size: 16pt;
+ margin: 0px;
+}
+
+p {
+ margin: 0px;
+}
+
+canvas {
+ border: 1px solid black;
+ cursor: crosshair;
+}
diff --git a/example/whiteboard/public/client.js b/example/whiteboard/public/client.js
new file mode 100644
index 0000000..21d9f90
--- /dev/null
+++ b/example/whiteboard/public/client.js
@@ -0,0 +1,189 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+function Whiteboard(canvasId) {
+ this.initCanvas(canvasId);
+
+ // Define accepted commands
+ this.messageHandlers = {
+ initCommands: this.initCommands.bind(this),
+ drawLine: this.drawLine.bind(this),
+ clear: this.clear.bind(this)
+ };
+
+ // Initial state
+ this.lastPoint = null;
+ this.mouseDown = false;
+ this.color = {
+ r: 0,
+ g: 0,
+ b: 0
+ };
+};
+
+Whiteboard.prototype.connect = function() {
+ var url = "ws://" + document.URL.substr(7).split('/')[0];
+
+ var wsCtor = window['MozWebSocket'] ? MozWebSocket : WebSocket;
+ this.socket = new wsCtor(url, 'whiteboard-example');
+
+ this.socket.onmessage = this.handleWebsocketMessage.bind(this);
+ this.socket.onclose = this.handleWebsocketClose.bind(this);
+
+ this.addCanvasEventListeners();
+};
+
+Whiteboard.prototype.handleWebsocketMessage = function(message) {
+ try {
+ var command = JSON.parse(message.data);
+ }
+ catch(e) { /* do nothing */ }
+
+ if (command) {
+ this.dispatchCommand(command);
+ }
+};
+
+Whiteboard.prototype.handleWebsocketClose = function() {
+ alert("WebSocket Connection Closed.");
+};
+
+Whiteboard.prototype.dispatchCommand = function(command) {
+ // Do we have a handler function for this command?
+ var handler = this.messageHandlers[command.msg];
+ if (typeof(handler) === 'function') {
+ // If so, call it and pass the parameter data
+ handler.call(this, command.data);
+ }
+};
+
+Whiteboard.prototype.initCommands = function(commandList) {
+ /* Upon connection, the contents of the whiteboard
+ are drawn by replaying all commands since the
+ last time it was cleared */
+ commandList.forEach(function(command) {
+ this.dispatchCommand(command);
+ }.bind(this));
+};
+
+Whiteboard.prototype.sendClear = function() {
+ this.socket.send(JSON.stringify({ msg: 'clear' }));
+};
+
+Whiteboard.prototype.setColor = function(r,g,b) {
+ this.color = {
+ r: r,
+ g: g,
+ b: b
+ };
+};
+
+Whiteboard.prototype.drawLine = function(data) {
+ // Set the color
+ var color = data.color;
+ this.ctx.strokeStyle = 'rgb(' + color.r + "," + color.g + "," + color.b +')';
+
+ this.ctx.beginPath();
+
+ var points = data.points;
+ // Starting point
+ this.ctx.moveTo(points[0]+0.5, points[1]+0.5);
+
+ // Ending point
+ this.ctx.lineTo(points[2]+0.5, points[3]+0.5);
+
+ this.ctx.stroke();
+};
+
+Whiteboard.prototype.clear = function() {
+ this.canvas.width = this.canvas.width;
+};
+
+Whiteboard.prototype.handleMouseDown = function(event) {
+ this.mouseDown = true;
+ this.lastPoint = this.resolveMousePosition(event);
+};
+
+Whiteboard.prototype.handleMouseUp = function(event) {
+ this.mouseDown = false;
+ this.lastPoint = null;
+};
+
+Whiteboard.prototype.handleMouseMove = function(event) {
+ if (!this.mouseDown) { return; }
+
+ var currentPoint = this.resolveMousePosition(event);
+
+ // Send a draw command to the server.
+ // The actual line is drawn when the command
+ // is received back from the server.
+ this.socket.send(JSON.stringify({
+ msg: 'drawLine',
+ data: {
+ color: this.color,
+ points: [
+ this.lastPoint.x,
+ this.lastPoint.y,
+ currentPoint.x,
+ currentPoint.y
+ ]
+ }
+ }));
+
+ this.lastPoint = currentPoint;
+};
+
+Whiteboard.prototype.initCanvas = function(canvasId) {
+ this.canvasId = canvasId;
+ this.canvas = document.getElementById(canvasId);
+ this.ctx = this.canvas.getContext('2d');
+ this.initCanvasOffset();
+};
+
+Whiteboard.prototype.initCanvasOffset = function() {
+ this.offsetX = this.offsetY = 0;
+ var element = this.canvas;
+ if (element.offsetParent) {
+ do {
+ this.offsetX += element.offsetLeft;
+ this.offsetY += element.offsetTop;
+ }
+ while ((element = element.offsetParent));
+ }
+};
+
+Whiteboard.prototype.addCanvasEventListeners = function() {
+ this.canvas.addEventListener(
+ 'mousedown', this.handleMouseDown.bind(this), false);
+
+ window.document.addEventListener(
+ 'mouseup', this.handleMouseUp.bind(this), false);
+
+ this.canvas.addEventListener(
+ 'mousemove', this.handleMouseMove.bind(this), false);
+};
+
+Whiteboard.prototype.resolveMousePosition = function(event) {
+ var x, y;
+ if (event.offsetX) {
+ x = event.offsetX;
+ y = event.offsetY;
+ } else {
+ x = event.layerX - this.offsetX;
+ y = event.layerY - this.offsetY;
+ }
+ return { x: x, y: y };
+};
diff --git a/example/whiteboard/whiteboard.js b/example/whiteboard/whiteboard.js
new file mode 100644
index 0000000..0cd259f
--- /dev/null
+++ b/example/whiteboard/whiteboard.js
@@ -0,0 +1,93 @@
+#!/usr/bin/env node
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var WebSocketServer = require('../../lib/websocket').server;
+var express = require('express');
+
+var app = express.createServer();
+
+app.configure(function() {
+ app.use(express.static(__dirname + "/public"));
+ app.set('views', __dirname);
+ app.set('view engine', 'ejs');
+});
+app.get('/', function(req, res) {
+ res.render('index', { layout: false });
+});
+app.listen(8080);
+
+
+var wsServer = new WebSocketServer({
+ httpServer: app,
+
+ // Firefox 7 alpha has a bug that drops the
+ // connection on large fragmented messages
+ fragmentOutgoingMessages: false
+});
+
+var connections = [];
+var canvasCommands = [];
+
+wsServer.on('request', function(request) {
+ var connection = request.accept('whiteboard-example', request.origin);
+ connections.push(connection);
+
+ console.log(connection.remoteAddress + " connected - Protocol Version " + connection.webSocketVersion);
+
+ // Send all the existing canvas commands to the new client
+ connection.sendUTF(JSON.stringify({
+ msg: "initCommands",
+ data: canvasCommands
+ }));
+
+ // Handle closed connections
+ connection.on('close', function() {
+ console.log(connection.remoteAddress + " disconnected");
+
+ var index = connections.indexOf(connection);
+ if (index !== -1) {
+ // remove the connection from the pool
+ connections.splice(index, 1);
+ }
+ });
+
+ // Handle incoming messages
+ connection.on('message', function(message) {
+ if (message.type === 'utf8') {
+ try {
+ var command = JSON.parse(message.utf8Data);
+
+ if (command.msg === 'clear') {
+ canvasCommands = [];
+ }
+ else {
+ canvasCommands.push(command);
+ }
+
+ // rebroadcast command to all clients
+ connections.forEach(function(destination) {
+ destination.sendUTF(message.utf8Data);
+ });
+ }
+ catch(e) {
+ // do nothing if there's an error.
+ }
+ }
+ });
+});
+
+console.log("Whiteboard test app ready");
diff --git a/gulpfile.js b/gulpfile.js
new file mode 100644
index 0000000..b515b92
--- /dev/null
+++ b/gulpfile.js
@@ -0,0 +1,14 @@
+/**
+ * Dependencies.
+ */
+var gulp = require('gulp');
+var jshint = require('gulp-jshint');
+
+gulp.task('lint', function() {
+ return gulp.src(['gulpfile.js', 'lib/**/*.js', 'test/**/*.js'])
+ .pipe(jshint('.jshintrc'))
+ .pipe(jshint.reporter('jshint-stylish', {verbose: true}))
+ .pipe(jshint.reporter('fail'));
+});
+
+gulp.task('default', gulp.series('lint'));
diff --git a/index.js b/index.js
new file mode 100644
index 0000000..573969f
--- /dev/null
+++ b/index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/websocket'); \ No newline at end of file
diff --git a/lib/BufferUtil.fallback.js b/lib/BufferUtil.fallback.js
new file mode 100644
index 0000000..de18bfb
--- /dev/null
+++ b/lib/BufferUtil.fallback.js
@@ -0,0 +1,52 @@
+/*!
+ * Copied from:
+ * ws: a node.js websocket client
+ * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
+ * MIT Licensed
+ */
+
+/* jshint -W086 */
+
+module.exports.BufferUtil = {
+ merge: function(mergedBuffer, buffers) {
+ var offset = 0;
+ for (var i = 0, l = buffers.length; i < l; ++i) {
+ var buf = buffers[i];
+ buf.copy(mergedBuffer, offset);
+ offset += buf.length;
+ }
+ },
+ mask: function(source, mask, output, offset, length) {
+ var maskNum = mask.readUInt32LE(0, true);
+ var i = 0;
+ for (; i < length - 3; i += 4) {
+ var num = maskNum ^ source.readUInt32LE(i, true);
+ if (num < 0) { num = 4294967296 + num; }
+ output.writeUInt32LE(num, offset + i, true);
+ }
+ switch (length % 4) {
+ case 3: output[offset + i + 2] = source[i + 2] ^ mask[2];
+ case 2: output[offset + i + 1] = source[i + 1] ^ mask[1];
+ case 1: output[offset + i] = source[i] ^ mask[0];
+ case 0:
+ }
+ },
+ unmask: function(data, mask) {
+ var maskNum = mask.readUInt32LE(0, true);
+ var length = data.length;
+ var i = 0;
+ for (; i < length - 3; i += 4) {
+ var num = maskNum ^ data.readUInt32LE(i, true);
+ if (num < 0) { num = 4294967296 + num; }
+ data.writeUInt32LE(num, i, true);
+ }
+ switch (length % 4) {
+ case 3: data[i + 2] = data[i + 2] ^ mask[2];
+ case 2: data[i + 1] = data[i + 1] ^ mask[1];
+ case 1: data[i] = data[i] ^ mask[0];
+ case 0:
+ }
+ }
+};
+
+/* jshint +W086 */ \ No newline at end of file
diff --git a/lib/BufferUtil.js b/lib/BufferUtil.js
new file mode 100644
index 0000000..fa37c80
--- /dev/null
+++ b/lib/BufferUtil.js
@@ -0,0 +1,17 @@
+/*!
+ * Copied from:
+ * ws: a node.js websocket client
+ * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
+ * MIT Licensed
+ */
+
+try {
+ module.exports = require('../build/Release/bufferutil');
+} catch (e) { try {
+ module.exports = require('../build/default/bufferutil');
+} catch (e) { try {
+ module.exports = require('./BufferUtil.fallback');
+} catch (e) {
+ console.error('bufferutil.node seems to not have been built. Run npm install.');
+ throw e;
+}}}
diff --git a/lib/Deprecation.js b/lib/Deprecation.js
new file mode 100644
index 0000000..094f160
--- /dev/null
+++ b/lib/Deprecation.js
@@ -0,0 +1,32 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var Deprecation = {
+ disableWarnings: false,
+
+ deprecationWarningMap: {
+
+ },
+
+ warn: function(deprecationName) {
+ if (!this.disableWarnings && this.deprecationWarningMap[deprecationName]) {
+ console.warn('DEPRECATION WARNING: ' + this.deprecationWarningMap[deprecationName]);
+ this.deprecationWarningMap[deprecationName] = false;
+ }
+ }
+};
+
+module.exports = Deprecation;
diff --git a/lib/Validation.fallback.js b/lib/Validation.fallback.js
new file mode 100644
index 0000000..6160f88
--- /dev/null
+++ b/lib/Validation.fallback.js
@@ -0,0 +1,12 @@
+/*!
+ * UTF-8 Validation Fallback Code originally from:
+ * ws: a node.js websocket client
+ * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
+ * MIT Licensed
+ */
+
+module.exports.Validation = {
+ isValidUTF8: function() {
+ return true;
+ }
+};
diff --git a/lib/Validation.js b/lib/Validation.js
new file mode 100644
index 0000000..b4106e8
--- /dev/null
+++ b/lib/Validation.js
@@ -0,0 +1,17 @@
+/*!
+ * UTF-8 Validation Code originally from:
+ * ws: a node.js websocket client
+ * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
+ * MIT Licensed
+ */
+
+try {
+ module.exports = require('../build/Release/validation');
+} catch (e) { try {
+ module.exports = require('../build/default/validation');
+} catch (e) { try {
+ module.exports = require('./Validation.fallback');
+} catch (e) {
+ console.error('validation.node seems not to have been built. Run npm install.');
+ throw e;
+}}}
diff --git a/lib/W3CWebSocket.js b/lib/W3CWebSocket.js
new file mode 100644
index 0000000..4305fb6
--- /dev/null
+++ b/lib/W3CWebSocket.js
@@ -0,0 +1,257 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var WebSocketClient = require('./WebSocketClient');
+var toBuffer = require('typedarray-to-buffer');
+var yaeti = require('yaeti');
+
+
+const CONNECTING = 0;
+const OPEN = 1;
+const CLOSING = 2;
+const CLOSED = 3;
+
+
+module.exports = W3CWebSocket;
+
+
+function W3CWebSocket(url, protocols, origin, headers, requestOptions, clientConfig) {
+ // Make this an EventTarget.
+ yaeti.EventTarget.call(this);
+
+ // Sanitize clientConfig.
+ clientConfig = clientConfig || {};
+ clientConfig.assembleFragments = true; // Required in the W3C API.
+
+ var self = this;
+
+ this._url = url;
+ this._readyState = CONNECTING;
+ this._protocol = undefined;
+ this._extensions = '';
+ this._bufferedAmount = 0; // Hack, always 0.
+ this._binaryType = 'arraybuffer'; // TODO: Should be 'blob' by default, but Node has no Blob.
+
+ // The WebSocketConnection instance.
+ this._connection = undefined;
+
+ // WebSocketClient instance.
+ this._client = new WebSocketClient(clientConfig);
+
+ this._client.on('connect', function(connection) {
+ onConnect.call(self, connection);
+ });
+
+ this._client.on('connectFailed', function() {
+ onConnectFailed.call(self);
+ });
+
+ this._client.connect(url, protocols, origin, headers, requestOptions);
+}
+
+
+// Expose W3C read only attributes.
+Object.defineProperties(W3CWebSocket.prototype, {
+ url: { get: function() { return this._url; } },
+ readyState: { get: function() { return this._readyState; } },
+ protocol: { get: function() { return this._protocol; } },
+ extensions: { get: function() { return this._extensions; } },
+ bufferedAmount: { get: function() { return this._bufferedAmount; } }
+});
+
+
+// Expose W3C write/read attributes.
+Object.defineProperties(W3CWebSocket.prototype, {
+ binaryType: {
+ get: function() {
+ return this._binaryType;
+ },
+ set: function(type) {
+ // TODO: Just 'arraybuffer' supported.
+ if (type !== 'arraybuffer') {
+ throw new SyntaxError('just "arraybuffer" type allowed for "binaryType" attribute');
+ }
+ this._binaryType = type;
+ }
+ }
+});
+
+
+// Expose W3C readyState constants into the WebSocket instance as W3C states.
+[['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) {
+ Object.defineProperty(W3CWebSocket.prototype, property[0], {
+ get: function() { return property[1]; }
+ });
+});
+
+// Also expone W3C readyState constants into the WebSocket class (not defined by the W3C,
+// but there are so many libs relying on them).
+[['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) {
+ Object.defineProperty(W3CWebSocket, property[0], {
+ get: function() { return property[1]; }
+ });
+});
+
+
+W3CWebSocket.prototype.send = function(data) {
+ if (this._readyState !== OPEN) {
+ throw new Error('cannot call send() while not connected');
+ }
+
+ // Text.
+ if (typeof data === 'string' || data instanceof String) {
+ this._connection.sendUTF(data);
+ }
+ // Binary.
+ else {
+ // Node Buffer.
+ if (data instanceof Buffer) {
+ this._connection.sendBytes(data);
+ }
+ // If ArrayBuffer or ArrayBufferView convert it to Node Buffer.
+ else if (data.byteLength || data.byteLength === 0) {
+ data = toBuffer(data);
+ this._connection.sendBytes(data);
+ }
+ else {
+ throw new Error('unknown binary data:', data);
+ }
+ }
+};
+
+
+W3CWebSocket.prototype.close = function(code, reason) {
+ switch(this._readyState) {
+ case CONNECTING:
+ // NOTE: We don't have the WebSocketConnection instance yet so no
+ // way to close the TCP connection.
+ // Artificially invoke the onConnectFailed event.
+ onConnectFailed.call(this);
+ // And close if it connects after a while.
+ this._client.on('connect', function(connection) {
+ if (code) {
+ connection.close(code, reason);
+ } else {
+ connection.close();
+ }
+ });
+ break;
+ case OPEN:
+ this._readyState = CLOSING;
+ if (code) {
+ this._connection.close(code, reason);
+ } else {
+ this._connection.close();
+ }
+ break;
+ case CLOSING:
+ case CLOSED:
+ break;
+ }
+};
+
+
+/**
+ * Private API.
+ */
+
+
+function createCloseEvent(code, reason) {
+ var event = new yaeti.Event('close');
+
+ event.code = code;
+ event.reason = reason;
+ event.wasClean = (typeof code === 'undefined' || code === 1000);
+
+ return event;
+}
+
+
+function createMessageEvent(data) {
+ var event = new yaeti.Event('message');
+
+ event.data = data;
+
+ return event;
+}
+
+
+function onConnect(connection) {
+ var self = this;
+
+ this._readyState = OPEN;
+ this._connection = connection;
+ this._protocol = connection.protocol;
+ this._extensions = connection.extensions;
+
+ this._connection.on('close', function(code, reason) {
+ onClose.call(self, code, reason);
+ });
+
+ this._connection.on('message', function(msg) {
+ onMessage.call(self, msg);
+ });
+
+ this.dispatchEvent(new yaeti.Event('open'));
+}
+
+
+function onConnectFailed() {
+ destroy.call(this);
+ this._readyState = CLOSED;
+
+ try {
+ this.dispatchEvent(new yaeti.Event('error'));
+ } finally {
+ this.dispatchEvent(createCloseEvent(1006, 'connection failed'));
+ }
+}
+
+
+function onClose(code, reason) {
+ destroy.call(this);
+ this._readyState = CLOSED;
+
+ this.dispatchEvent(createCloseEvent(code, reason || ''));
+}
+
+
+function onMessage(message) {
+ if (message.utf8Data) {
+ this.dispatchEvent(createMessageEvent(message.utf8Data));
+ }
+ else if (message.binaryData) {
+ // Must convert from Node Buffer to ArrayBuffer.
+ // TODO: or to a Blob (which does not exist in Node!).
+ if (this.binaryType === 'arraybuffer') {
+ var buffer = message.binaryData;
+ var arraybuffer = new ArrayBuffer(buffer.length);
+ var view = new Uint8Array(arraybuffer);
+ for (var i=0, len=buffer.length; i<len; ++i) {
+ view[i] = buffer[i];
+ }
+ this.dispatchEvent(createMessageEvent(arraybuffer));
+ }
+ }
+}
+
+
+function destroy() {
+ this._client.removeAllListeners();
+ if (this._connection) {
+ this._connection.removeAllListeners();
+ }
+}
diff --git a/lib/WebSocketClient.js b/lib/WebSocketClient.js
new file mode 100644
index 0000000..4b4abb2
--- /dev/null
+++ b/lib/WebSocketClient.js
@@ -0,0 +1,348 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var utils = require('./utils');
+var extend = utils.extend;
+var util = require('util');
+var EventEmitter = require('events').EventEmitter;
+var http = require('http');
+var https = require('https');
+var url = require('url');
+var crypto = require('crypto');
+var WebSocketConnection = require('./WebSocketConnection');
+
+var protocolSeparators = [
+ '(', ')', '<', '>', '@',
+ ',', ';', ':', '\\', '\"',
+ '/', '[', ']', '?', '=',
+ '{', '}', ' ', String.fromCharCode(9)
+];
+
+function WebSocketClient(config) {
+ // Superclass Constructor
+ EventEmitter.call(this);
+
+ // TODO: Implement extensions
+
+ this.config = {
+ // 1MiB max frame size.
+ maxReceivedFrameSize: 0x100000,
+
+ // 8MiB max message size, only applicable if
+ // assembleFragments is true
+ maxReceivedMessageSize: 0x800000,
+
+ // Outgoing messages larger than fragmentationThreshold will be
+ // split into multiple fragments.
+ fragmentOutgoingMessages: true,
+
+ // Outgoing frames are fragmented if they exceed this threshold.
+ // Default is 16KiB
+ fragmentationThreshold: 0x4000,
+
+ // Which version of the protocol to use for this session. This
+ // option will be removed once the protocol is finalized by the IETF
+ // It is only available to ease the transition through the
+ // intermediate draft protocol versions.
+ // At present, it only affects the name of the Origin header.
+ webSocketVersion: 13,
+
+ // If true, fragmented messages will be automatically assembled
+ // and the full message will be emitted via a 'message' event.
+ // If false, each frame will be emitted via a 'frame' event and
+ // the application will be responsible for aggregating multiple
+ // fragmented frames. Single-frame messages will emit a 'message'
+ // event in addition to the 'frame' event.
+ // Most users will want to leave this set to 'true'
+ assembleFragments: true,
+
+ // The Nagle Algorithm makes more efficient use of network resources
+ // by introducing a small delay before sending small packets so that
+ // multiple messages can be batched together before going onto the
+ // wire. This however comes at the cost of latency, so the default
+ // is to disable it. If you don't need low latency and are streaming
+ // lots of small messages, you can change this to 'false'
+ disableNagleAlgorithm: true,
+
+ // The number of milliseconds to wait after sending a close frame
+ // for an acknowledgement to come back before giving up and just
+ // closing the socket.
+ closeTimeout: 5000,
+
+ // Options to pass to https.connect if connecting via TLS
+ tlsOptions: {}
+ };
+
+ if (config) {
+ var tlsOptions;
+ if (config.tlsOptions) {
+ tlsOptions = config.tlsOptions;
+ delete config.tlsOptions;
+ }
+ else {
+ tlsOptions = {};
+ }
+ extend(this.config, config);
+ extend(this.config.tlsOptions, tlsOptions);
+ }
+
+ this._req = null;
+
+ switch (this.config.webSocketVersion) {
+ case 8:
+ case 13:
+ break;
+ default:
+ throw new Error('Requested webSocketVersion is not supported. Allowed values are 8 and 13.');
+ }
+}
+
+util.inherits(WebSocketClient, EventEmitter);
+
+WebSocketClient.prototype.connect = function(requestUrl, protocols, origin, headers, extraRequestOptions) {
+ var self = this;
+ if (typeof(protocols) === 'string') {
+ if (protocols.length > 0) {
+ protocols = [protocols];
+ }
+ else {
+ protocols = [];
+ }
+ }
+ if (!(protocols instanceof Array)) {
+ protocols = [];
+ }
+ this.protocols = protocols;
+ this.origin = origin;
+
+ if (typeof(requestUrl) === 'string') {
+ this.url = url.parse(requestUrl);
+ }
+ else {
+ this.url = requestUrl; // in case an already parsed url is passed in.
+ }
+ if (!this.url.protocol) {
+ throw new Error('You must specify a full WebSocket URL, including protocol.');
+ }
+ if (!this.url.host) {
+ throw new Error('You must specify a full WebSocket URL, including hostname. Relative URLs are not supported.');
+ }
+
+ this.secure = (this.url.protocol === 'wss:');
+
+ // validate protocol characters:
+ this.protocols.forEach(function(protocol) {
+ for (var i=0; i < protocol.length; i ++) {
+ var charCode = protocol.charCodeAt(i);
+ var character = protocol.charAt(i);
+ if (charCode < 0x0021 || charCode > 0x007E || protocolSeparators.indexOf(character) !== -1) {
+ throw new Error('Protocol list contains invalid character "' + String.fromCharCode(charCode) + '"');
+ }
+ }
+ });
+
+ var defaultPorts = {
+ 'ws:': '80',
+ 'wss:': '443'
+ };
+
+ if (!this.url.port) {
+ this.url.port = defaultPorts[this.url.protocol];
+ }
+
+ var nonce = new Buffer(16);
+ for (var i=0; i < 16; i++) {
+ nonce[i] = Math.round(Math.random()*0xFF);
+ }
+ this.base64nonce = nonce.toString('base64');
+
+ var hostHeaderValue = this.url.hostname;
+ if ((this.url.protocol === 'ws:' && this.url.port !== '80') ||
+ (this.url.protocol === 'wss:' && this.url.port !== '443')) {
+ hostHeaderValue += (':' + this.url.port);
+ }
+
+ var reqHeaders = headers || {};
+ extend(reqHeaders, {
+ 'Upgrade': 'websocket',
+ 'Connection': 'Upgrade',
+ 'Sec-WebSocket-Version': this.config.webSocketVersion.toString(10),
+ 'Sec-WebSocket-Key': this.base64nonce,
+ 'Host': hostHeaderValue
+ });
+
+ if (this.protocols.length > 0) {
+ reqHeaders['Sec-WebSocket-Protocol'] = this.protocols.join(', ');
+ }
+ if (this.origin) {
+ if (this.config.webSocketVersion === 13) {
+ reqHeaders['Origin'] = this.origin;
+ }
+ else if (this.config.webSocketVersion === 8) {
+ reqHeaders['Sec-WebSocket-Origin'] = this.origin;
+ }
+ }
+
+ // TODO: Implement extensions
+
+ var pathAndQuery;
+ // Ensure it begins with '/'.
+ if (this.url.pathname) {
+ pathAndQuery = this.url.path;
+ }
+ else if (this.url.path) {
+ pathAndQuery = '/' + this.url.path;
+ }
+ else {
+ pathAndQuery = '/';
+ }
+
+ function handleRequestError(error) {
+ self._req = null;
+ self.emit('connectFailed', error);
+ }
+
+ var requestOptions = {
+ agent: false
+ };
+ if (extraRequestOptions) {
+ extend(requestOptions, extraRequestOptions);
+ }
+ // These options are always overridden by the library. The user is not
+ // allowed to specify these directly.
+ extend(requestOptions, {
+ hostname: this.url.hostname,
+ port: this.url.port,
+ method: 'GET',
+ path: pathAndQuery,
+ headers: reqHeaders
+ });
+ if (this.secure) {
+ for (var key in self.config.tlsOptions) {
+ if (self.config.tlsOptions.hasOwnProperty(key)) {
+ requestOptions[key] = self.config.tlsOptions[key];
+ }
+ }
+ }
+
+ var req = this._req = (this.secure ? https : http).request(requestOptions);
+ req.on('upgrade', function handleRequestUpgrade(response, socket, head) {
+ self._req = null;
+ req.removeListener('error', handleRequestError);
+ self.socket = socket;
+ self.response = response;
+ self.firstDataChunk = head;
+ self.validateHandshake();
+ });
+ req.on('error', handleRequestError);
+
+ req.on('response', function(response) {
+ self._req = null;
+ if (utils.eventEmitterListenerCount(self, 'httpResponse') > 0) {
+ self.emit('httpResponse', response, self);
+ if (response.socket) {
+ response.socket.end();
+ }
+ }
+ else {
+ var headerDumpParts = [];
+ for (var headerName in response.headers) {
+ headerDumpParts.push(headerName + ': ' + response.headers[headerName]);
+ }
+ self.failHandshake(
+ 'Server responded with a non-101 status: ' +
+ response.statusCode +
+ '\nResponse Headers Follow:\n' +
+ headerDumpParts.join('\n') + '\n'
+ );
+ }
+ });
+ req.end();
+};
+
+WebSocketClient.prototype.validateHandshake = function() {
+ var headers = this.response.headers;
+
+ if (this.protocols.length > 0) {
+ this.protocol = headers['sec-websocket-protocol'];
+ if (this.protocol) {
+ if (this.protocols.indexOf(this.protocol) === -1) {
+ this.failHandshake('Server did not respond with a requested protocol.');
+ return;
+ }
+ }
+ else {
+ this.failHandshake('Expected a Sec-WebSocket-Protocol header.');
+ return;
+ }
+ }
+
+ if (!(headers['connection'] && headers['connection'].toLocaleLowerCase() === 'upgrade')) {
+ this.failHandshake('Expected a Connection: Upgrade header from the server');
+ return;
+ }
+
+ if (!(headers['upgrade'] && headers['upgrade'].toLocaleLowerCase() === 'websocket')) {
+ this.failHandshake('Expected an Upgrade: websocket header from the server');
+ return;
+ }
+
+ var sha1 = crypto.createHash('sha1');
+ sha1.update(this.base64nonce + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11');
+ var expectedKey = sha1.digest('base64');
+
+ if (!headers['sec-websocket-accept']) {
+ this.failHandshake('Expected Sec-WebSocket-Accept header from server');
+ return;
+ }
+
+ if (headers['sec-websocket-accept'] !== expectedKey) {
+ this.failHandshake('Sec-WebSocket-Accept header from server didn\'t match expected value of ' + expectedKey);
+ return;
+ }
+
+ // TODO: Support extensions
+
+ this.succeedHandshake();
+};
+
+WebSocketClient.prototype.failHandshake = function(errorDescription) {
+ if (this.socket && this.socket.writable) {
+ this.socket.end();
+ }
+ this.emit('connectFailed', new Error(errorDescription));
+};
+
+WebSocketClient.prototype.succeedHandshake = function() {
+ var connection = new WebSocketConnection(this.socket, [], this.protocol, true, this.config);
+
+ connection.webSocketVersion = this.config.webSocketVersion;
+ connection._addSocketEventListeners();
+
+ this.emit('connect', connection);
+ if (this.firstDataChunk.length > 0) {
+ connection.handleSocketData(this.firstDataChunk);
+ }
+ this.firstDataChunk = null;
+};
+
+WebSocketClient.prototype.abort = function() {
+ if (this._req) {
+ this._req.abort();
+ }
+};
+
+module.exports = WebSocketClient;
diff --git a/lib/WebSocketConnection.js b/lib/WebSocketConnection.js
new file mode 100644
index 0000000..fd87264
--- /dev/null
+++ b/lib/WebSocketConnection.js
@@ -0,0 +1,889 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var util = require('util');
+var utils = require('./utils');
+var EventEmitter = require('events').EventEmitter;
+var WebSocketFrame = require('./WebSocketFrame');
+var BufferList = require('../vendor/FastBufferList');
+var Validation = require('./Validation').Validation;
+
+// Connected, fully-open, ready to send and receive frames
+const STATE_OPEN = 'open';
+// Received a close frame from the remote peer
+const STATE_PEER_REQUESTED_CLOSE = 'peer_requested_close';
+// Sent close frame to remote peer. No further data can be sent.
+const STATE_ENDING = 'ending';
+// Connection is fully closed. No further data can be sent or received.
+const STATE_CLOSED = 'closed';
+
+var setImmediateImpl = ('setImmediate' in global) ?
+ global.setImmediate.bind(global) :
+ process.nextTick.bind(process);
+
+var idCounter = 0;
+
+function WebSocketConnection(socket, extensions, protocol, maskOutgoingPackets, config) {
+ this._debug = utils.BufferingLogger('websocket:connection', ++idCounter);
+ this._debug('constructor');
+
+ if (this._debug.enabled) {
+ instrumentSocketForDebugging(this, socket);
+ }
+
+ // Superclass Constructor
+ EventEmitter.call(this);
+
+ this._pingListenerCount = 0;
+ this.on('newListener', function(ev) {
+ if (ev === 'ping'){
+ this._pingListenerCount++;
+ }
+ }).on('removeListener', function(ev) {
+ if (ev === 'ping') {
+ this._pingListenerCount--;
+ }
+ });
+
+ this.config = config;
+ this.socket = socket;
+ this.protocol = protocol;
+ this.extensions = extensions;
+ this.remoteAddress = socket.remoteAddress;
+ this.closeReasonCode = -1;
+ this.closeDescription = null;
+ this.closeEventEmitted = false;
+
+ // We have to mask outgoing packets if we're acting as a WebSocket client.
+ this.maskOutgoingPackets = maskOutgoingPackets;
+
+ // We re-use the same buffers for the mask and frame header for all frames
+ // received on each connection to avoid a small memory allocation for each
+ // frame.
+ this.maskBytes = new Buffer(4);
+ this.frameHeader = new Buffer(10);
+
+ // the BufferList will handle the data streaming in
+ this.bufferList = new BufferList();
+
+ // Prepare for receiving first frame
+ this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
+ this.fragmentationSize = 0; // data received so far...
+ this.frameQueue = [];
+
+ // Various bits of connection state
+ this.connected = true;
+ this.state = STATE_OPEN;
+ this.waitingForCloseResponse = false;
+ // Received TCP FIN, socket's readable stream is finished.
+ this.receivedEnd = false;
+
+ this.closeTimeout = this.config.closeTimeout;
+ this.assembleFragments = this.config.assembleFragments;
+ this.maxReceivedMessageSize = this.config.maxReceivedMessageSize;
+
+ this.outputBufferFull = false;
+ this.inputPaused = false;
+ this.receivedDataHandler = this.processReceivedData.bind(this);
+ this._closeTimerHandler = this.handleCloseTimer.bind(this);
+
+ // Disable nagle algorithm?
+ this.socket.setNoDelay(this.config.disableNagleAlgorithm);
+
+ // Make sure there is no socket inactivity timeout
+ this.socket.setTimeout(0);
+
+ if (this.config.keepalive && !this.config.useNativeKeepalive) {
+ if (typeof(this.config.keepaliveInterval) !== 'number') {
+ throw new Error('keepaliveInterval must be specified and numeric ' +
+ 'if keepalive is true.');
+ }
+ this._keepaliveTimerHandler = this.handleKeepaliveTimer.bind(this);
+ this.setKeepaliveTimer();
+
+ if (this.config.dropConnectionOnKeepaliveTimeout) {
+ if (typeof(this.config.keepaliveGracePeriod) !== 'number') {
+ throw new Error('keepaliveGracePeriod must be specified and ' +
+ 'numeric if dropConnectionOnKeepaliveTimeout ' +
+ 'is true.');
+ }
+ this._gracePeriodTimerHandler = this.handleGracePeriodTimer.bind(this);
+ }
+ }
+ else if (this.config.keepalive && this.config.useNativeKeepalive) {
+ if (!('setKeepAlive' in this.socket)) {
+ throw new Error('Unable to use native keepalive: unsupported by ' +
+ 'this version of Node.');
+ }
+ this.socket.setKeepAlive(true, this.config.keepaliveInterval);
+ }
+
+ // The HTTP Client seems to subscribe to socket error events
+ // and re-dispatch them in such a way that doesn't make sense
+ // for users of our client, so we want to make sure nobody
+ // else is listening for error events on the socket besides us.
+ this.socket.removeAllListeners('error');
+}
+
+WebSocketConnection.CLOSE_REASON_NORMAL = 1000;
+WebSocketConnection.CLOSE_REASON_GOING_AWAY = 1001;
+WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR = 1002;
+WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT = 1003;
+WebSocketConnection.CLOSE_REASON_RESERVED = 1004; // Reserved value. Undefined meaning.
+WebSocketConnection.CLOSE_REASON_NOT_PROVIDED = 1005; // Not to be used on the wire
+WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006; // Not to be used on the wire
+WebSocketConnection.CLOSE_REASON_INVALID_DATA = 1007;
+WebSocketConnection.CLOSE_REASON_POLICY_VIOLATION = 1008;
+WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG = 1009;
+WebSocketConnection.CLOSE_REASON_EXTENSION_REQUIRED = 1010;
+WebSocketConnection.CLOSE_REASON_INTERNAL_SERVER_ERROR = 1011;
+WebSocketConnection.CLOSE_REASON_TLS_HANDSHAKE_FAILED = 1015; // Not to be used on the wire
+
+WebSocketConnection.CLOSE_DESCRIPTIONS = {
+ 1000: 'Normal connection closure',
+ 1001: 'Remote peer is going away',
+ 1002: 'Protocol error',
+ 1003: 'Unprocessable input',
+ 1004: 'Reserved',
+ 1005: 'Reason not provided',
+ 1006: 'Abnormal closure, no further detail available',
+ 1007: 'Invalid data received',
+ 1008: 'Policy violation',
+ 1009: 'Message too big',
+ 1010: 'Extension requested by client is required',
+ 1011: 'Internal Server Error',
+ 1015: 'TLS Handshake Failed'
+};
+
+function validateCloseReason(code) {
+ if (code < 1000) {
+ // Status codes in the range 0-999 are not used
+ return false;
+ }
+ if (code >= 1000 && code <= 2999) {
+ // Codes from 1000 - 2999 are reserved for use by the protocol. Only
+ // a few codes are defined, all others are currently illegal.
+ return [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011].indexOf(code) !== -1;
+ }
+ if (code >= 3000 && code <= 3999) {
+ // Reserved for use by libraries, frameworks, and applications.
+ // Should be registered with IANA. Interpretation of these codes is
+ // undefined by the WebSocket protocol.
+ return true;
+ }
+ if (code >= 4000 && code <= 4999) {
+ // Reserved for private use. Interpretation of these codes is
+ // undefined by the WebSocket protocol.
+ return true;
+ }
+ if (code >= 5000) {
+ return false;
+ }
+}
+
+util.inherits(WebSocketConnection, EventEmitter);
+
+WebSocketConnection.prototype._addSocketEventListeners = function() {
+ this.socket.on('error', this.handleSocketError.bind(this));
+ this.socket.on('end', this.handleSocketEnd.bind(this));
+ this.socket.on('close', this.handleSocketClose.bind(this));
+ this.socket.on('drain', this.handleSocketDrain.bind(this));
+ this.socket.on('pause', this.handleSocketPause.bind(this));
+ this.socket.on('resume', this.handleSocketResume.bind(this));
+ this.socket.on('data', this.handleSocketData.bind(this));
+};
+
+// set or reset the keepalive timer when data is received.
+WebSocketConnection.prototype.setKeepaliveTimer = function() {
+ this._debug('setKeepaliveTimer');
+ if (!this.config.keepalive) { return; }
+ this.clearKeepaliveTimer();
+ this.clearGracePeriodTimer();
+ this._keepaliveTimeoutID = setTimeout(this._keepaliveTimerHandler, this.config.keepaliveInterval);
+};
+
+WebSocketConnection.prototype.clearKeepaliveTimer = function() {
+ if (this._keepaliveTimeoutID) {
+ clearTimeout(this._keepaliveTimeoutID);
+ }
+};
+
+// No data has been received within config.keepaliveTimeout ms.
+WebSocketConnection.prototype.handleKeepaliveTimer = function() {
+ this._debug('handleKeepaliveTimer');
+ this._keepaliveTimeoutID = null;
+ this.ping();
+
+ // If we are configured to drop connections if the client doesn't respond
+ // then set the grace period timer.
+ if (this.config.dropConnectionOnKeepaliveTimeout) {
+ this.setGracePeriodTimer();
+ }
+ else {
+ // Otherwise reset the keepalive timer to send the next ping.
+ this.setKeepaliveTimer();
+ }
+};
+
+WebSocketConnection.prototype.setGracePeriodTimer = function() {
+ this._debug('setGracePeriodTimer');
+ this.clearGracePeriodTimer();
+ this._gracePeriodTimeoutID = setTimeout(this._gracePeriodTimerHandler, this.config.keepaliveGracePeriod);
+};
+
+WebSocketConnection.prototype.clearGracePeriodTimer = function() {
+ if (this._gracePeriodTimeoutID) {
+ clearTimeout(this._gracePeriodTimeoutID);
+ }
+};
+
+WebSocketConnection.prototype.handleGracePeriodTimer = function() {
+ this._debug('handleGracePeriodTimer');
+ // If this is called, the client has not responded and is assumed dead.
+ this._gracePeriodTimeoutID = null;
+ this.drop(WebSocketConnection.CLOSE_REASON_ABNORMAL, 'Peer not responding.', true);
+};
+
+WebSocketConnection.prototype.handleSocketData = function(data) {
+ this._debug('handleSocketData');
+ // Reset the keepalive timer when receiving data of any kind.
+ this.setKeepaliveTimer();
+
+ // Add received data to our bufferList, which efficiently holds received
+ // data chunks in a linked list of Buffer objects.
+ this.bufferList.write(data);
+
+ this.processReceivedData();
+};
+
+WebSocketConnection.prototype.processReceivedData = function() {
+ this._debug('processReceivedData');
+ // If we're not connected, we should ignore any data remaining on the buffer.
+ if (!this.connected) { return; }
+
+ // Receiving/parsing is expected to be halted when paused.
+ if (this.inputPaused) { return; }
+
+ var frame = this.currentFrame;
+
+ // WebSocketFrame.prototype.addData returns true if all data necessary to
+ // parse the frame was available. It returns false if we are waiting for
+ // more data to come in on the wire.
+ if (!frame.addData(this.bufferList)) { this._debug('-- insufficient data for frame'); return; }
+
+ var self = this;
+
+ // Handle possible parsing errors
+ if (frame.protocolError) {
+ // Something bad happened.. get rid of this client.
+ this._debug('-- protocol error');
+ process.nextTick(function() {
+ self.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, frame.dropReason);
+ });
+ return;
+ }
+ else if (frame.frameTooLarge) {
+ this._debug('-- frame too large');
+ process.nextTick(function() {
+ self.drop(WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG, frame.dropReason);
+ });
+ return;
+ }
+
+ // For now since we don't support extensions, all RSV bits are illegal
+ if (frame.rsv1 || frame.rsv2 || frame.rsv3) {
+ this._debug('-- illegal rsv flag');
+ process.nextTick(function() {
+ self.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
+ 'Unsupported usage of rsv bits without negotiated extension.');
+ });
+ return;
+ }
+
+ if (!this.assembleFragments) {
+ this._debug('-- emitting frame');
+ process.nextTick(function() { self.emit('frame', frame); });
+ }
+
+ process.nextTick(function() { self.processFrame(frame); });
+
+ this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
+
+ // If there's data remaining, schedule additional processing, but yield
+ // for now so that other connections have a chance to have their data
+ // processed. We use setImmediate here instead of process.nextTick to
+ // explicitly indicate that we wish for other I/O to be handled first.
+ if (this.bufferList.length > 0) {
+ setImmediateImpl(this.receivedDataHandler);
+ }
+};
+
+WebSocketConnection.prototype.handleSocketError = function(error) {
+ this._debug('handleSocketError: %j', error);
+ this.closeReasonCode = WebSocketConnection.CLOSE_REASON_ABNORMAL;
+ this.closeDescription = 'Socket Error: ' + error.syscall + ' ' + error.code;
+ this.connected = false;
+ this.state = STATE_CLOSED;
+ this.fragmentationSize = 0;
+ if (utils.eventEmitterListenerCount(this, 'error') > 0) {
+ this.emit('error', error);
+ }
+ this.socket.destroy(error);
+ this._debug.printOutput();
+};
+
+WebSocketConnection.prototype.handleSocketEnd = function() {
+ this._debug('handleSocketEnd: received socket end. state = %s', this.state);
+ this.receivedEnd = true;
+ if (this.state === STATE_CLOSED) {
+ // When using the TLS module, sometimes the socket will emit 'end'
+ // after it emits 'close'. I don't think that's correct behavior,
+ // but we should deal with it gracefully by ignoring it.
+ this._debug(' --- Socket \'end\' after \'close\'');
+ return;
+ }
+ if (this.state !== STATE_PEER_REQUESTED_CLOSE &&
+ this.state !== STATE_ENDING) {
+ this._debug(' --- UNEXPECTED socket end.');
+ this.socket.end();
+ }
+};
+
+WebSocketConnection.prototype.handleSocketClose = function(hadError) {
+ this._debug('handleSocketClose: received socket close');
+ this.socketHadError = hadError;
+ this.connected = false;
+ this.state = STATE_CLOSED;
+ // If closeReasonCode is still set to -1 at this point then we must
+ // not have received a close frame!!
+ if (this.closeReasonCode === -1) {
+ this.closeReasonCode = WebSocketConnection.CLOSE_REASON_ABNORMAL;
+ this.closeDescription = 'Connection dropped by remote peer.';
+ }
+ this.clearCloseTimer();
+ this.clearKeepaliveTimer();
+ this.clearGracePeriodTimer();
+ if (!this.closeEventEmitted) {
+ this.closeEventEmitted = true;
+ this._debug('-- Emitting WebSocketConnection close event');
+ this.emit('close', this.closeReasonCode, this.closeDescription);
+ }
+};
+
+WebSocketConnection.prototype.handleSocketDrain = function() {
+ this._debug('handleSocketDrain: socket drain event');
+ this.outputBufferFull = false;
+ this.emit('drain');
+};
+
+WebSocketConnection.prototype.handleSocketPause = function() {
+ this._debug('handleSocketPause: socket pause event');
+ this.inputPaused = true;
+ this.emit('pause');
+};
+
+WebSocketConnection.prototype.handleSocketResume = function() {
+ this._debug('handleSocketResume: socket resume event');
+ this.inputPaused = false;
+ this.emit('resume');
+ this.processReceivedData();
+};
+
+WebSocketConnection.prototype.pause = function() {
+ this._debug('pause: pause requested');
+ this.socket.pause();
+};
+
+WebSocketConnection.prototype.resume = function() {
+ this._debug('resume: resume requested');
+ this.socket.resume();
+};
+
+WebSocketConnection.prototype.close = function(reasonCode, description) {
+ if (this.connected) {
+ this._debug('close: Initating clean WebSocket close sequence.');
+ if ('number' !== typeof reasonCode) {
+ reasonCode = WebSocketConnection.CLOSE_REASON_NORMAL;
+ }
+ if (!validateCloseReason(reasonCode)) {
+ throw new Error('Close code ' + reasonCode + ' is not valid.');
+ }
+ if ('string' !== typeof description) {
+ description = WebSocketConnection.CLOSE_DESCRIPTIONS[reasonCode];
+ }
+ this.closeReasonCode = reasonCode;
+ this.closeDescription = description;
+ this.setCloseTimer();
+ this.sendCloseFrame(this.closeReasonCode, this.closeDescription);
+ this.state = STATE_ENDING;
+ this.connected = false;
+ }
+};
+
+WebSocketConnection.prototype.drop = function(reasonCode, description, skipCloseFrame) {
+ this._debug('drop');
+ if (typeof(reasonCode) !== 'number') {
+ reasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR;
+ }
+
+ if (typeof(description) !== 'string') {
+ // If no description is provided, try to look one up based on the
+ // specified reasonCode.
+ description = WebSocketConnection.CLOSE_DESCRIPTIONS[reasonCode];
+ }
+
+ this._debug('Forcefully dropping connection. skipCloseFrame: %s, code: %d, description: %s',
+ skipCloseFrame, reasonCode, description
+ );
+
+ this.closeReasonCode = reasonCode;
+ this.closeDescription = description;
+ this.frameQueue = [];
+ this.fragmentationSize = 0;
+ if (!skipCloseFrame) {
+ this.sendCloseFrame(reasonCode, description);
+ }
+ this.connected = false;
+ this.state = STATE_CLOSED;
+ this.clearCloseTimer();
+ this.clearKeepaliveTimer();
+ this.clearGracePeriodTimer();
+
+ if (!this.closeEventEmitted) {
+ this.closeEventEmitted = true;
+ this._debug('Emitting WebSocketConnection close event');
+ this.emit('close', this.closeReasonCode, this.closeDescription);
+ }
+
+ this._debug('Drop: destroying socket');
+ this.socket.destroy();
+};
+
+WebSocketConnection.prototype.setCloseTimer = function() {
+ this._debug('setCloseTimer');
+ this.clearCloseTimer();
+ this._debug('Setting close timer');
+ this.waitingForCloseResponse = true;
+ this.closeTimer = setTimeout(this._closeTimerHandler, this.closeTimeout);
+};
+
+WebSocketConnection.prototype.clearCloseTimer = function() {
+ this._debug('clearCloseTimer');
+ if (this.closeTimer) {
+ this._debug('Clearing close timer');
+ clearTimeout(this.closeTimer);
+ this.waitingForCloseResponse = false;
+ this.closeTimer = null;
+ }
+};
+
+WebSocketConnection.prototype.handleCloseTimer = function() {
+ this._debug('handleCloseTimer');
+ this.closeTimer = null;
+ if (this.waitingForCloseResponse) {
+ this._debug('Close response not received from client. Forcing socket end.');
+ this.waitingForCloseResponse = false;
+ this.state = STATE_CLOSED;
+ this.socket.end();
+ }
+};
+
+WebSocketConnection.prototype.processFrame = function(frame) {
+ this._debug('processFrame');
+ this._debug(' -- frame: %s', frame);
+
+ // Any non-control opcode besides 0x00 (continuation) received in the
+ // middle of a fragmented message is illegal.
+ if (this.frameQueue.length !== 0 && (frame.opcode > 0x00 && frame.opcode < 0x08)) {
+ this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
+ 'Illegal frame opcode 0x' + frame.opcode.toString(16) + ' ' +
+ 'received in middle of fragmented message.');
+ return;
+ }
+
+ switch(frame.opcode) {
+ case 0x02: // WebSocketFrame.BINARY_FRAME
+ this._debug('-- Binary Frame');
+ if (this.assembleFragments) {
+ if (frame.fin) {
+ // Complete single-frame message received
+ this._debug('---- Emitting \'message\' event');
+ this.emit('message', {
+ type: 'binary',
+ binaryData: frame.binaryPayload
+ });
+ }
+ else {
+ // beginning of a fragmented message
+ this.frameQueue.push(frame);
+ this.fragmentationSize = frame.length;
+ }
+ }
+ break;
+ case 0x01: // WebSocketFrame.TEXT_FRAME
+ this._debug('-- Text Frame');
+ if (this.assembleFragments) {
+ if (frame.fin) {
+ if (!Validation.isValidUTF8(frame.binaryPayload)) {
+ this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA,
+ 'Invalid UTF-8 Data Received');
+ return;
+ }
+ // Complete single-frame message received
+ this._debug('---- Emitting \'message\' event');
+ this.emit('message', {
+ type: 'utf8',
+ utf8Data: frame.binaryPayload.toString('utf8')
+ });
+ }
+ else {
+ // beginning of a fragmented message
+ this.frameQueue.push(frame);
+ this.fragmentationSize = frame.length;
+ }
+ }
+ break;
+ case 0x00: // WebSocketFrame.CONTINUATION
+ this._debug('-- Continuation Frame');
+ if (this.assembleFragments) {
+ if (this.frameQueue.length === 0) {
+ this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
+ 'Unexpected Continuation Frame');
+ return;
+ }
+
+ this.fragmentationSize += frame.length;
+
+ if (this.fragmentationSize > this.maxReceivedMessageSize) {
+ this.drop(WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG,
+ 'Maximum message size exceeded.');
+ return;
+ }
+
+ this.frameQueue.push(frame);
+
+ if (frame.fin) {
+ // end of fragmented message, so we process the whole
+ // message now. We also have to decode the utf-8 data
+ // for text frames after combining all the fragments.
+ var bytesCopied = 0;
+ var binaryPayload = new Buffer(this.fragmentationSize);
+ var opcode = this.frameQueue[0].opcode;
+ this.frameQueue.forEach(function (currentFrame) {
+ currentFrame.binaryPayload.copy(binaryPayload, bytesCopied);
+ bytesCopied += currentFrame.binaryPayload.length;
+ });
+ this.frameQueue = [];
+ this.fragmentationSize = 0;
+
+ switch (opcode) {
+ case 0x02: // WebSocketOpcode.BINARY_FRAME
+ this.emit('message', {
+ type: 'binary',
+ binaryData: binaryPayload
+ });
+ break;
+ case 0x01: // WebSocketOpcode.TEXT_FRAME
+ if (!Validation.isValidUTF8(binaryPayload)) {
+ this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA,
+ 'Invalid UTF-8 Data Received');
+ return;
+ }
+ this.emit('message', {
+ type: 'utf8',
+ utf8Data: binaryPayload.toString('utf8')
+ });
+ break;
+ default:
+ this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
+ 'Unexpected first opcode in fragmentation sequence: 0x' + opcode.toString(16));
+ return;
+ }
+ }
+ }
+ break;
+ case 0x09: // WebSocketFrame.PING
+ this._debug('-- Ping Frame');
+
+ if (this._pingListenerCount > 0) {
+ // logic to emit the ping frame: this is only done when a listener is known to exist
+ // Expose a function allowing the user to override the default ping() behavior
+ var cancelled = false;
+ var cancel = function() {
+ cancelled = true;
+ };
+ this.emit('ping', cancel, frame.binaryPayload);
+
+ // Only send a pong if the client did not indicate that he would like to cancel
+ if (!cancelled) {
+ this.pong(frame.binaryPayload);
+ }
+ }
+ else {
+ this.pong(frame.binaryPayload);
+ }
+
+ break;
+ case 0x0A: // WebSocketFrame.PONG
+ this._debug('-- Pong Frame');
+ this.emit('pong', frame.binaryPayload);
+ break;
+ case 0x08: // WebSocketFrame.CONNECTION_CLOSE
+ this._debug('-- Close Frame');
+ if (this.waitingForCloseResponse) {
+ // Got response to our request to close the connection.
+ // Close is complete, so we just hang up.
+ this._debug('---- Got close response from peer. Completing closing handshake.');
+ this.clearCloseTimer();
+ this.waitingForCloseResponse = false;
+ this.state = STATE_CLOSED;
+ this.socket.end();
+ return;
+ }
+
+ this._debug('---- Closing handshake initiated by peer.');
+ // Got request from other party to close connection.
+ // Send back acknowledgement and then hang up.
+ this.state = STATE_PEER_REQUESTED_CLOSE;
+ var respondCloseReasonCode;
+
+ // Make sure the close reason provided is legal according to
+ // the protocol spec. Providing no close status is legal.
+ // WebSocketFrame sets closeStatus to -1 by default, so if it
+ // is still -1, then no status was provided.
+ if (frame.invalidCloseFrameLength) {
+ this.closeReasonCode = 1005; // 1005 = No reason provided.
+ respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR;
+ }
+ else if (frame.closeStatus === -1 || validateCloseReason(frame.closeStatus)) {
+ this.closeReasonCode = frame.closeStatus;
+ respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_NORMAL;
+ }
+ else {
+ this.closeReasonCode = frame.closeStatus;
+ respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR;
+ }
+
+ // If there is a textual description in the close frame, extract it.
+ if (frame.binaryPayload.length > 1) {
+ if (!Validation.isValidUTF8(frame.binaryPayload)) {
+ this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA,
+ 'Invalid UTF-8 Data Received');
+ return;
+ }
+ this.closeDescription = frame.binaryPayload.toString('utf8');
+ }
+ else {
+ this.closeDescription = WebSocketConnection.CLOSE_DESCRIPTIONS[this.closeReasonCode];
+ }
+ this._debug(
+ '------ Remote peer %s - code: %d - %s - close frame payload length: %d',
+ this.remoteAddress, this.closeReasonCode,
+ this.closeDescription, frame.length
+ );
+ this._debug('------ responding to remote peer\'s close request.');
+ this.sendCloseFrame(respondCloseReasonCode, null);
+ this.connected = false;
+ break;
+ default:
+ this._debug('-- Unrecognized Opcode %d', frame.opcode);
+ this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
+ 'Unrecognized Opcode: 0x' + frame.opcode.toString(16));
+ break;
+ }
+};
+
+WebSocketConnection.prototype.send = function(data, cb) {
+ this._debug('send');
+ if (Buffer.isBuffer(data)) {
+ this.sendBytes(data, cb);
+ }
+ else if (typeof(data['toString']) === 'function') {
+ this.sendUTF(data, cb);
+ }
+ else {
+ throw new Error('Data provided must either be a Node Buffer or implement toString()');
+ }
+};
+
+WebSocketConnection.prototype.sendUTF = function(data, cb) {
+ data = new Buffer(data.toString(), 'utf8');
+ this._debug('sendUTF: %d bytes', data.length);
+ var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
+ frame.opcode = 0x01; // WebSocketOpcode.TEXT_FRAME
+ frame.binaryPayload = data;
+ this.fragmentAndSend(frame, cb);
+};
+
+WebSocketConnection.prototype.sendBytes = function(data, cb) {
+ this._debug('sendBytes');
+ if (!Buffer.isBuffer(data)) {
+ throw new Error('You must pass a Node Buffer object to WebSocketConnection.prototype.sendBytes()');
+ }
+ var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
+ frame.opcode = 0x02; // WebSocketOpcode.BINARY_FRAME
+ frame.binaryPayload = data;
+ this.fragmentAndSend(frame, cb);
+};
+
+WebSocketConnection.prototype.ping = function(data) {
+ this._debug('ping');
+ var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
+ frame.opcode = 0x09; // WebSocketOpcode.PING
+ frame.fin = true;
+ if (data) {
+ if (!Buffer.isBuffer(data)) {
+ data = new Buffer(data.toString(), 'utf8');
+ }
+ if (data.length > 125) {
+ this._debug('WebSocket: Data for ping is longer than 125 bytes. Truncating.');
+ data = data.slice(0,124);
+ }
+ frame.binaryPayload = data;
+ }
+ this.sendFrame(frame);
+};
+
+// Pong frames have to echo back the contents of the data portion of the
+// ping frame exactly, byte for byte.
+WebSocketConnection.prototype.pong = function(binaryPayload) {
+ this._debug('pong');
+ var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
+ frame.opcode = 0x0A; // WebSocketOpcode.PONG
+ if (Buffer.isBuffer(binaryPayload) && binaryPayload.length > 125) {
+ this._debug('WebSocket: Data for pong is longer than 125 bytes. Truncating.');
+ binaryPayload = binaryPayload.slice(0,124);
+ }
+ frame.binaryPayload = binaryPayload;
+ frame.fin = true;
+ this.sendFrame(frame);
+};
+
+WebSocketConnection.prototype.fragmentAndSend = function(frame, cb) {
+ this._debug('fragmentAndSend');
+ if (frame.opcode > 0x07) {
+ throw new Error('You cannot fragment control frames.');
+ }
+
+ var threshold = this.config.fragmentationThreshold;
+ var length = frame.binaryPayload.length;
+
+ // Send immediately if fragmentation is disabled or the message is not
+ // larger than the fragmentation threshold.
+ if (!this.config.fragmentOutgoingMessages || (frame.binaryPayload && length <= threshold)) {
+ frame.fin = true;
+ this.sendFrame(frame, cb);
+ return;
+ }
+
+ var numFragments = Math.ceil(length / threshold);
+ var sentFragments = 0;
+ var sentCallback = function fragmentSentCallback(err) {
+ if (err) {
+ if (typeof cb === 'function') {
+ // pass only the first error
+ cb(err);
+ cb = null;
+ }
+ return;
+ }
+ ++sentFragments;
+ if ((sentFragments === numFragments) && (typeof cb === 'function')) {
+ cb();
+ }
+ };
+ for (var i=1; i <= numFragments; i++) {
+ var currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
+
+ // continuation opcode except for first frame.
+ currentFrame.opcode = (i === 1) ? frame.opcode : 0x00;
+
+ // fin set on last frame only
+ currentFrame.fin = (i === numFragments);
+
+ // length is likely to be shorter on the last fragment
+ var currentLength = (i === numFragments) ? length - (threshold * (i-1)) : threshold;
+ var sliceStart = threshold * (i-1);
+
+ // Slice the right portion of the original payload
+ currentFrame.binaryPayload = frame.binaryPayload.slice(sliceStart, sliceStart + currentLength);
+
+ this.sendFrame(currentFrame, sentCallback);
+ }
+};
+
+WebSocketConnection.prototype.sendCloseFrame = function(reasonCode, description, cb) {
+ if (typeof(reasonCode) !== 'number') {
+ reasonCode = WebSocketConnection.CLOSE_REASON_NORMAL;
+ }
+
+ this._debug('sendCloseFrame state: %s, reasonCode: %d, description: %s', this.state, reasonCode, description);
+
+ if (this.state !== STATE_OPEN && this.state !== STATE_PEER_REQUESTED_CLOSE) { return; }
+
+ var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
+ frame.fin = true;
+ frame.opcode = 0x08; // WebSocketOpcode.CONNECTION_CLOSE
+ frame.closeStatus = reasonCode;
+ if (typeof(description) === 'string') {
+ frame.binaryPayload = new Buffer(description, 'utf8');
+ }
+
+ this.sendFrame(frame, cb);
+ this.socket.end();
+};
+
+WebSocketConnection.prototype.sendFrame = function(frame, cb) {
+ this._debug('sendFrame');
+ frame.mask = this.maskOutgoingPackets;
+ var flushed = this.socket.write(frame.toBuffer(), cb);
+ this.outputBufferFull = !flushed;
+ return flushed;
+};
+
+module.exports = WebSocketConnection;
+
+
+
+function instrumentSocketForDebugging(connection, socket) {
+ /* jshint loopfunc: true */
+ if (!connection._debug.enabled) { return; }
+
+ var originalSocketEmit = socket.emit;
+ socket.emit = function(event) {
+ connection._debug('||| Socket Event \'%s\'', event);
+ originalSocketEmit.apply(this, arguments);
+ };
+
+ for (var key in socket) {
+ if ('function' !== typeof(socket[key])) { continue; }
+ if (['emit'].indexOf(key) !== -1) { continue; }
+ (function(key) {
+ var original = socket[key];
+ if (key === 'on') {
+ socket[key] = function proxyMethod__EventEmitter__On() {
+ connection._debug('||| Socket method called: %s (%s)', key, arguments[0]);
+ return original.apply(this, arguments);
+ };
+ return;
+ }
+ socket[key] = function proxyMethod() {
+ connection._debug('||| Socket method called: %s', key);
+ return original.apply(this, arguments);
+ };
+ })(key);
+ }
+}
diff --git a/lib/WebSocketFrame.js b/lib/WebSocketFrame.js
new file mode 100644
index 0000000..859e879
--- /dev/null
+++ b/lib/WebSocketFrame.js
@@ -0,0 +1,279 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var bufferUtil = require('./BufferUtil').BufferUtil;
+
+const DECODE_HEADER = 1;
+const WAITING_FOR_16_BIT_LENGTH = 2;
+const WAITING_FOR_64_BIT_LENGTH = 3;
+const WAITING_FOR_MASK_KEY = 4;
+const WAITING_FOR_PAYLOAD = 5;
+const COMPLETE = 6;
+
+// WebSocketConnection will pass shared buffer objects for maskBytes and
+// frameHeader into the constructor to avoid tons of small memory allocations
+// for each frame we have to parse. This is only used for parsing frames
+// we receive off the wire.
+function WebSocketFrame(maskBytes, frameHeader, config) {
+ this.maskBytes = maskBytes;
+ this.frameHeader = frameHeader;
+ this.config = config;
+ this.maxReceivedFrameSize = config.maxReceivedFrameSize;
+ this.protocolError = false;
+ this.frameTooLarge = false;
+ this.invalidCloseFrameLength = false;
+ this.parseState = DECODE_HEADER;
+ this.closeStatus = -1;
+}
+
+WebSocketFrame.prototype.addData = function(bufferList) {
+ if (this.parseState === DECODE_HEADER) {
+ if (bufferList.length >= 2) {
+ bufferList.joinInto(this.frameHeader, 0, 0, 2);
+ bufferList.advance(2);
+ var firstByte = this.frameHeader[0];
+ var secondByte = this.frameHeader[1];
+
+ this.fin = Boolean(firstByte & 0x80);
+ this.rsv1 = Boolean(firstByte & 0x40);
+ this.rsv2 = Boolean(firstByte & 0x20);
+ this.rsv3 = Boolean(firstByte & 0x10);
+ this.mask = Boolean(secondByte & 0x80);
+
+ this.opcode = firstByte & 0x0F;
+ this.length = secondByte & 0x7F;
+
+ // Control frame sanity check
+ if (this.opcode >= 0x08) {
+ if (this.length > 125) {
+ this.protocolError = true;
+ this.dropReason = 'Illegal control frame longer than 125 bytes.';
+ return true;
+ }
+ if (!this.fin) {
+ this.protocolError = true;
+ this.dropReason = 'Control frames must not be fragmented.';
+ return true;
+ }
+ }
+
+ if (this.length === 126) {
+ this.parseState = WAITING_FOR_16_BIT_LENGTH;
+ }
+ else if (this.length === 127) {
+ this.parseState = WAITING_FOR_64_BIT_LENGTH;
+ }
+ else {
+ this.parseState = WAITING_FOR_MASK_KEY;
+ }
+ }
+ }
+ if (this.parseState === WAITING_FOR_16_BIT_LENGTH) {
+ if (bufferList.length >= 2) {
+ bufferList.joinInto(this.frameHeader, 2, 0, 2);
+ bufferList.advance(2);
+ this.length = this.frameHeader.readUInt16BE(2, true);
+ this.parseState = WAITING_FOR_MASK_KEY;
+ }
+ }
+ else if (this.parseState === WAITING_FOR_64_BIT_LENGTH) {
+ if (bufferList.length >= 8) {
+ bufferList.joinInto(this.frameHeader, 2, 0, 8);
+ bufferList.advance(8);
+ var lengthPair = [
+ this.frameHeader.readUInt32BE(2, true),
+ this.frameHeader.readUInt32BE(2+4, true)
+ ];
+
+ if (lengthPair[0] !== 0) {
+ this.protocolError = true;
+ this.dropReason = 'Unsupported 64-bit length frame received';
+ return true;
+ }
+ this.length = lengthPair[1];
+ this.parseState = WAITING_FOR_MASK_KEY;
+ }
+ }
+
+ if (this.parseState === WAITING_FOR_MASK_KEY) {
+ if (this.mask) {
+ if (bufferList.length >= 4) {
+ bufferList.joinInto(this.maskBytes, 0, 0, 4);
+ bufferList.advance(4);
+ this.parseState = WAITING_FOR_PAYLOAD;
+ }
+ }
+ else {
+ this.parseState = WAITING_FOR_PAYLOAD;
+ }
+ }
+
+ if (this.parseState === WAITING_FOR_PAYLOAD) {
+ if (this.length > this.maxReceivedFrameSize) {
+ this.frameTooLarge = true;
+ this.dropReason = 'Frame size of ' + this.length.toString(10) +
+ ' bytes exceeds maximum accepted frame size';
+ return true;
+ }
+
+ if (this.length === 0) {
+ this.binaryPayload = new Buffer(0);
+ this.parseState = COMPLETE;
+ return true;
+ }
+ if (bufferList.length >= this.length) {
+ this.binaryPayload = bufferList.take(this.length);
+ bufferList.advance(this.length);
+ if (this.mask) {
+ bufferUtil.unmask(this.binaryPayload, this.maskBytes);
+ // xor(this.binaryPayload, this.maskBytes, 0);
+ }
+
+ if (this.opcode === 0x08) { // WebSocketOpcode.CONNECTION_CLOSE
+ if (this.length === 1) {
+ // Invalid length for a close frame. Must be zero or at least two.
+ this.binaryPayload = new Buffer(0);
+ this.invalidCloseFrameLength = true;
+ }
+ if (this.length >= 2) {
+ this.closeStatus = this.binaryPayload.readUInt16BE(0, true);
+ this.binaryPayload = this.binaryPayload.slice(2);
+ }
+ }
+
+ this.parseState = COMPLETE;
+ return true;
+ }
+ }
+ return false;
+};
+
+WebSocketFrame.prototype.throwAwayPayload = function(bufferList) {
+ if (bufferList.length >= this.length) {
+ bufferList.advance(this.length);
+ this.parseState = COMPLETE;
+ return true;
+ }
+ return false;
+};
+
+WebSocketFrame.prototype.toBuffer = function(nullMask) {
+ var maskKey;
+ var headerLength = 2;
+ var data;
+ var outputPos;
+ var firstByte = 0x00;
+ var secondByte = 0x00;
+
+ if (this.fin) {
+ firstByte |= 0x80;
+ }
+ if (this.rsv1) {
+ firstByte |= 0x40;
+ }
+ if (this.rsv2) {
+ firstByte |= 0x20;
+ }
+ if (this.rsv3) {
+ firstByte |= 0x10;
+ }
+ if (this.mask) {
+ secondByte |= 0x80;
+ }
+
+ firstByte |= (this.opcode & 0x0F);
+
+ // the close frame is a special case because the close reason is
+ // prepended to the payload data.
+ if (this.opcode === 0x08) {
+ this.length = 2;
+ if (this.binaryPayload) {
+ this.length += this.binaryPayload.length;
+ }
+ data = new Buffer(this.length);
+ data.writeUInt16BE(this.closeStatus, 0, true);
+ if (this.length > 2) {
+ this.binaryPayload.copy(data, 2);
+ }
+ }
+ else if (this.binaryPayload) {
+ data = this.binaryPayload;
+ this.length = data.length;
+ }
+ else {
+ this.length = 0;
+ }
+
+ if (this.length <= 125) {
+ // encode the length directly into the two-byte frame header
+ secondByte |= (this.length & 0x7F);
+ }
+ else if (this.length > 125 && this.length <= 0xFFFF) {
+ // Use 16-bit length
+ secondByte |= 126;
+ headerLength += 2;
+ }
+ else if (this.length > 0xFFFF) {
+ // Use 64-bit length
+ secondByte |= 127;
+ headerLength += 8;
+ }
+
+ var output = new Buffer(this.length + headerLength + (this.mask ? 4 : 0));
+
+ // write the frame header
+ output[0] = firstByte;
+ output[1] = secondByte;
+
+ outputPos = 2;
+
+ if (this.length > 125 && this.length <= 0xFFFF) {
+ // write 16-bit length
+ output.writeUInt16BE(this.length, outputPos, true);
+ outputPos += 2;
+ }
+ else if (this.length > 0xFFFF) {
+ // write 64-bit length
+ output.writeUInt32BE(0x00000000, outputPos, true);
+ output.writeUInt32BE(this.length, outputPos + 4, true);
+ outputPos += 8;
+ }
+
+ if (this.mask) {
+ maskKey = nullMask ? 0 : (Math.random()*0xFFFFFFFF) | 0;
+ this.maskBytes.writeUInt32BE(maskKey, 0, true);
+
+ // write the mask key
+ this.maskBytes.copy(output, outputPos);
+ outputPos += 4;
+
+ if (data) {
+ bufferUtil.mask(data, this.maskBytes, output, outputPos, this.length);
+ }
+ }
+ else if (data) {
+ data.copy(output, outputPos);
+ }
+
+ return output;
+};
+
+WebSocketFrame.prototype.toString = function() {
+ return 'Opcode: ' + this.opcode + ', fin: ' + this.fin + ', length: ' + this.length + ', hasPayload: ' + Boolean(this.binaryPayload) + ', masked: ' + this.mask;
+};
+
+
+module.exports = WebSocketFrame;
diff --git a/lib/WebSocketRequest.js b/lib/WebSocketRequest.js
new file mode 100644
index 0000000..f4d9655
--- /dev/null
+++ b/lib/WebSocketRequest.js
@@ -0,0 +1,524 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var crypto = require('crypto');
+var util = require('util');
+var url = require('url');
+var EventEmitter = require('events').EventEmitter;
+var WebSocketConnection = require('./WebSocketConnection');
+
+var headerValueSplitRegExp = /,\s*/;
+var headerParamSplitRegExp = /;\s*/;
+var headerSanitizeRegExp = /[\r\n]/g;
+var xForwardedForSeparatorRegExp = /,\s*/;
+var separators = [
+ '(', ')', '<', '>', '@',
+ ',', ';', ':', '\\', '\"',
+ '/', '[', ']', '?', '=',
+ '{', '}', ' ', String.fromCharCode(9)
+];
+var controlChars = [String.fromCharCode(127) /* DEL */];
+for (var i=0; i < 31; i ++) {
+ /* US-ASCII Control Characters */
+ controlChars.push(String.fromCharCode(i));
+}
+
+var cookieNameValidateRegEx = /([\x00-\x20\x22\x28\x29\x2c\x2f\x3a-\x3f\x40\x5b-\x5e\x7b\x7d\x7f])/;
+var cookieValueValidateRegEx = /[^\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]/;
+var cookieValueDQuoteValidateRegEx = /^"[^"]*"$/;
+var controlCharsAndSemicolonRegEx = /[\x00-\x20\x3b]/g;
+
+var cookieSeparatorRegEx = /[;,] */;
+
+var httpStatusDescriptions = {
+ 100: 'Continue',
+ 101: 'Switching Protocols',
+ 200: 'OK',
+ 201: 'Created',
+ 203: 'Non-Authoritative Information',
+ 204: 'No Content',
+ 205: 'Reset Content',
+ 206: 'Partial Content',
+ 300: 'Multiple Choices',
+ 301: 'Moved Permanently',
+ 302: 'Found',
+ 303: 'See Other',
+ 304: 'Not Modified',
+ 305: 'Use Proxy',
+ 307: 'Temporary Redirect',
+ 400: 'Bad Request',
+ 401: 'Unauthorized',
+ 402: 'Payment Required',
+ 403: 'Forbidden',
+ 404: 'Not Found',
+ 406: 'Not Acceptable',
+ 407: 'Proxy Authorization Required',
+ 408: 'Request Timeout',
+ 409: 'Conflict',
+ 410: 'Gone',
+ 411: 'Length Required',
+ 412: 'Precondition Failed',
+ 413: 'Request Entity Too Long',
+ 414: 'Request-URI Too Long',
+ 415: 'Unsupported Media Type',
+ 416: 'Requested Range Not Satisfiable',
+ 417: 'Expectation Failed',
+ 426: 'Upgrade Required',
+ 500: 'Internal Server Error',
+ 501: 'Not Implemented',
+ 502: 'Bad Gateway',
+ 503: 'Service Unavailable',
+ 504: 'Gateway Timeout',
+ 505: 'HTTP Version Not Supported'
+};
+
+function WebSocketRequest(socket, httpRequest, serverConfig) {
+ // Superclass Constructor
+ EventEmitter.call(this);
+
+ this.socket = socket;
+ this.httpRequest = httpRequest;
+ this.resource = httpRequest.url;
+ this.remoteAddress = socket.remoteAddress;
+ this.remoteAddresses = [this.remoteAddress];
+ this.serverConfig = serverConfig;
+
+ // Watch for the underlying TCP socket closing before we call accept
+ this._socketIsClosing = false;
+ this._socketCloseHandler = this._handleSocketCloseBeforeAccept.bind(this);
+ this.socket.on('end', this._socketCloseHandler);
+ this.socket.on('close', this._socketCloseHandler);
+
+ this._resolved = false;
+}
+
+util.inherits(WebSocketRequest, EventEmitter);
+
+WebSocketRequest.prototype.readHandshake = function() {
+ var self = this;
+ var request = this.httpRequest;
+
+ // Decode URL
+ this.resourceURL = url.parse(this.resource, true);
+
+ this.host = request.headers['host'];
+ if (!this.host) {
+ throw new Error('Client must provide a Host header.');
+ }
+
+ this.key = request.headers['sec-websocket-key'];
+ if (!this.key) {
+ throw new Error('Client must provide a value for Sec-WebSocket-Key.');
+ }
+
+ this.webSocketVersion = parseInt(request.headers['sec-websocket-version'], 10);
+
+ if (!this.webSocketVersion || isNaN(this.webSocketVersion)) {
+ throw new Error('Client must provide a value for Sec-WebSocket-Version.');
+ }
+
+ switch (this.webSocketVersion) {
+ case 8:
+ case 13:
+ break;
+ default:
+ var e = new Error('Unsupported websocket client version: ' + this.webSocketVersion +
+ 'Only versions 8 and 13 are supported.');
+ e.httpCode = 426;
+ e.headers = {
+ 'Sec-WebSocket-Version': '13'
+ };
+ throw e;
+ }
+
+ if (this.webSocketVersion === 13) {
+ this.origin = request.headers['origin'];
+ }
+ else if (this.webSocketVersion === 8) {
+ this.origin = request.headers['sec-websocket-origin'];
+ }
+
+ // Protocol is optional.
+ var protocolString = request.headers['sec-websocket-protocol'];
+ this.protocolFullCaseMap = {};
+ this.requestedProtocols = [];
+ if (protocolString) {
+ var requestedProtocolsFullCase = protocolString.split(headerValueSplitRegExp);
+ requestedProtocolsFullCase.forEach(function(protocol) {
+ var lcProtocol = protocol.toLocaleLowerCase();
+ self.requestedProtocols.push(lcProtocol);
+ self.protocolFullCaseMap[lcProtocol] = protocol;
+ });
+ }
+
+ if (!this.serverConfig.ignoreXForwardedFor &&
+ request.headers['x-forwarded-for']) {
+ var immediatePeerIP = this.remoteAddress;
+ this.remoteAddresses = request.headers['x-forwarded-for']
+ .split(xForwardedForSeparatorRegExp);
+ this.remoteAddresses.push(immediatePeerIP);
+ this.remoteAddress = this.remoteAddresses[0];
+ }
+
+ // Extensions are optional.
+ var extensionsString = request.headers['sec-websocket-extensions'];
+ this.requestedExtensions = this.parseExtensions(extensionsString);
+
+ // Cookies are optional
+ var cookieString = request.headers['cookie'];
+ this.cookies = this.parseCookies(cookieString);
+};
+
+WebSocketRequest.prototype.parseExtensions = function(extensionsString) {
+ if (!extensionsString || extensionsString.length === 0) {
+ return [];
+ }
+ var extensions = extensionsString.toLocaleLowerCase().split(headerValueSplitRegExp);
+ extensions.forEach(function(extension, index, array) {
+ var params = extension.split(headerParamSplitRegExp);
+ var extensionName = params[0];
+ var extensionParams = params.slice(1);
+ extensionParams.forEach(function(rawParam, index, array) {
+ var arr = rawParam.split('=');
+ var obj = {
+ name: arr[0],
+ value: arr[1]
+ };
+ array.splice(index, 1, obj);
+ });
+ var obj = {
+ name: extensionName,
+ params: extensionParams
+ };
+ array.splice(index, 1, obj);
+ });
+ return extensions;
+};
+
+// This function adapted from node-cookie
+// https://github.com/shtylman/node-cookie
+WebSocketRequest.prototype.parseCookies = function(str) {
+ // Sanity Check
+ if (!str || typeof(str) !== 'string') {
+ return [];
+ }
+
+ var cookies = [];
+ var pairs = str.split(cookieSeparatorRegEx);
+
+ pairs.forEach(function(pair) {
+ var eq_idx = pair.indexOf('=');
+ if (eq_idx === -1) {
+ cookies.push({
+ name: pair,
+ value: null
+ });
+ return;
+ }
+
+ var key = pair.substr(0, eq_idx).trim();
+ var val = pair.substr(++eq_idx, pair.length).trim();
+
+ // quoted values
+ if ('"' === val[0]) {
+ val = val.slice(1, -1);
+ }
+
+ cookies.push({
+ name: key,
+ value: decodeURIComponent(val)
+ });
+ });
+
+ return cookies;
+};
+
+WebSocketRequest.prototype.accept = function(acceptedProtocol, allowedOrigin, cookies) {
+ this._verifyResolution();
+
+ // TODO: Handle extensions
+
+ var protocolFullCase;
+
+ if (acceptedProtocol) {
+ protocolFullCase = this.protocolFullCaseMap[acceptedProtocol.toLocaleLowerCase()];
+ if (typeof(protocolFullCase) === 'undefined') {
+ protocolFullCase = acceptedProtocol;
+ }
+ }
+ else {
+ protocolFullCase = acceptedProtocol;
+ }
+ this.protocolFullCaseMap = null;
+
+ // Create key validation hash
+ var sha1 = crypto.createHash('sha1');
+ sha1.update(this.key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11');
+ var acceptKey = sha1.digest('base64');
+
+ var response = 'HTTP/1.1 101 Switching Protocols\r\n' +
+ 'Upgrade: websocket\r\n' +
+ 'Connection: Upgrade\r\n' +
+ 'Sec-WebSocket-Accept: ' + acceptKey + '\r\n';
+
+ if (protocolFullCase) {
+ // validate protocol
+ for (var i=0; i < protocolFullCase.length; i++) {
+ var charCode = protocolFullCase.charCodeAt(i);
+ var character = protocolFullCase.charAt(i);
+ if (charCode < 0x21 || charCode > 0x7E || separators.indexOf(character) !== -1) {
+ this.reject(500);
+ throw new Error('Illegal character "' + String.fromCharCode(character) + '" in subprotocol.');
+ }
+ }
+ if (this.requestedProtocols.indexOf(acceptedProtocol) === -1) {
+ this.reject(500);
+ throw new Error('Specified protocol was not requested by the client.');
+ }
+
+ protocolFullCase = protocolFullCase.replace(headerSanitizeRegExp, '');
+ response += 'Sec-WebSocket-Protocol: ' + protocolFullCase + '\r\n';
+ }
+ this.requestedProtocols = null;
+
+ if (allowedOrigin) {
+ allowedOrigin = allowedOrigin.replace(headerSanitizeRegExp, '');
+ if (this.webSocketVersion === 13) {
+ response += 'Origin: ' + allowedOrigin + '\r\n';
+ }
+ else if (this.webSocketVersion === 8) {
+ response += 'Sec-WebSocket-Origin: ' + allowedOrigin + '\r\n';
+ }
+ }
+
+ if (cookies) {
+ if (!Array.isArray(cookies)) {
+ this.reject(500);
+ throw new Error('Value supplied for "cookies" argument must be an array.');
+ }
+ var seenCookies = {};
+ cookies.forEach(function(cookie) {
+ if (!cookie.name || !cookie.value) {
+ this.reject(500);
+ throw new Error('Each cookie to set must at least provide a "name" and "value"');
+ }
+
+ // Make sure there are no \r\n sequences inserted
+ cookie.name = cookie.name.replace(controlCharsAndSemicolonRegEx, '');
+ cookie.value = cookie.value.replace(controlCharsAndSemicolonRegEx, '');
+
+ if (seenCookies[cookie.name]) {
+ this.reject(500);
+ throw new Error('You may not specify the same cookie name twice.');
+ }
+ seenCookies[cookie.name] = true;
+
+ // token (RFC 2616, Section 2.2)
+ var invalidChar = cookie.name.match(cookieNameValidateRegEx);
+ if (invalidChar) {
+ this.reject(500);
+ throw new Error('Illegal character ' + invalidChar[0] + ' in cookie name');
+ }
+
+ // RFC 6265, Section 4.1.1
+ // *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) | %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
+ if (cookie.value.match(cookieValueDQuoteValidateRegEx)) {
+ invalidChar = cookie.value.slice(1, -1).match(cookieValueValidateRegEx);
+ } else {
+ invalidChar = cookie.value.match(cookieValueValidateRegEx);
+ }
+ if (invalidChar) {
+ this.reject(500);
+ throw new Error('Illegal character ' + invalidChar[0] + ' in cookie value');
+ }
+
+ var cookieParts = [cookie.name + '=' + cookie.value];
+
+ // RFC 6265, Section 4.1.1
+ // 'Path=' path-value | <any CHAR except CTLs or ';'>
+ if(cookie.path){
+ invalidChar = cookie.path.match(controlCharsAndSemicolonRegEx);
+ if (invalidChar) {
+ this.reject(500);
+ throw new Error('Illegal character ' + invalidChar[0] + ' in cookie path');
+ }
+ cookieParts.push('Path=' + cookie.path);
+ }
+
+ // RFC 6265, Section 4.1.2.3
+ // 'Domain=' subdomain
+ if (cookie.domain) {
+ if (typeof(cookie.domain) !== 'string') {
+ this.reject(500);
+ throw new Error('Domain must be specified and must be a string.');
+ }
+ invalidChar = cookie.domain.match(controlCharsAndSemicolonRegEx);
+ if (invalidChar) {
+ this.reject(500);
+ throw new Error('Illegal character ' + invalidChar[0] + ' in cookie domain');
+ }
+ cookieParts.push('Domain=' + cookie.domain.toLowerCase());
+ }
+
+ // RFC 6265, Section 4.1.1
+ //'Expires=' sane-cookie-date | Force Date object requirement by using only epoch
+ if (cookie.expires) {
+ if (!(cookie.expires instanceof Date)){
+ this.reject(500);
+ throw new Error('Value supplied for cookie "expires" must be a vaild date object');
+ }
+ cookieParts.push('Expires=' + cookie.expires.toGMTString());
+ }
+
+ // RFC 6265, Section 4.1.1
+ //'Max-Age=' non-zero-digit *DIGIT
+ if (cookie.maxage) {
+ var maxage = cookie.maxage;
+ if (typeof(maxage) === 'string') {
+ maxage = parseInt(maxage, 10);
+ }
+ if (isNaN(maxage) || maxage <= 0 ) {
+ this.reject(500);
+ throw new Error('Value supplied for cookie "maxage" must be a non-zero number');
+ }
+ maxage = Math.round(maxage);
+ cookieParts.push('Max-Age=' + maxage.toString(10));
+ }
+
+ // RFC 6265, Section 4.1.1
+ //'Secure;'
+ if (cookie.secure) {
+ if (typeof(cookie.secure) !== 'boolean') {
+ this.reject(500);
+ throw new Error('Value supplied for cookie "secure" must be of type boolean');
+ }
+ cookieParts.push('Secure');
+ }
+
+ // RFC 6265, Section 4.1.1
+ //'HttpOnly;'
+ if (cookie.httponly) {
+ if (typeof(cookie.httponly) !== 'boolean') {
+ this.reject(500);
+ throw new Error('Value supplied for cookie "httponly" must be of type boolean');
+ }
+ cookieParts.push('HttpOnly');
+ }
+
+ response += ('Set-Cookie: ' + cookieParts.join(';') + '\r\n');
+ }.bind(this));
+ }
+
+ // TODO: handle negotiated extensions
+ // if (negotiatedExtensions) {
+ // response += 'Sec-WebSocket-Extensions: ' + negotiatedExtensions.join(', ') + '\r\n';
+ // }
+
+ // Mark the request resolved now so that the user can't call accept or
+ // reject a second time.
+ this._resolved = true;
+ this.emit('requestResolved', this);
+
+ response += '\r\n';
+
+ var connection = new WebSocketConnection(this.socket, [], acceptedProtocol, false, this.serverConfig);
+ connection.webSocketVersion = this.webSocketVersion;
+ connection.remoteAddress = this.remoteAddress;
+ connection.remoteAddresses = this.remoteAddresses;
+
+ var self = this;
+
+ if (this._socketIsClosing) {
+ // Handle case when the client hangs up before we get a chance to
+ // accept the connection and send our side of the opening handshake.
+ cleanupFailedConnection(connection);
+ }
+ else {
+ this.socket.write(response, 'ascii', function(error) {
+ if (error) {
+ cleanupFailedConnection(connection);
+ return;
+ }
+
+ self._removeSocketCloseListeners();
+ connection._addSocketEventListeners();
+ });
+ }
+
+ this.emit('requestAccepted', connection);
+ return connection;
+};
+
+WebSocketRequest.prototype.reject = function(status, reason, extraHeaders) {
+ this._verifyResolution();
+
+ // Mark the request resolved now so that the user can't call accept or
+ // reject a second time.
+ this._resolved = true;
+ this.emit('requestResolved', this);
+
+ if (typeof(status) !== 'number') {
+ status = 403;
+ }
+ var response = 'HTTP/1.1 ' + status + ' ' + httpStatusDescriptions[status] + '\r\n' +
+ 'Connection: close\r\n';
+ if (reason) {
+ reason = reason.replace(headerSanitizeRegExp, '');
+ response += 'X-WebSocket-Reject-Reason: ' + reason + '\r\n';
+ }
+
+ if (extraHeaders) {
+ for (var key in extraHeaders) {
+ var sanitizedValue = extraHeaders[key].toString().replace(headerSanitizeRegExp, '');
+ var sanitizedKey = key.replace(headerSanitizeRegExp, '');
+ response += (sanitizedKey + ': ' + sanitizedValue + '\r\n');
+ }
+ }
+
+ response += '\r\n';
+ this.socket.end(response, 'ascii');
+
+ this.emit('requestRejected', this);
+};
+
+WebSocketRequest.prototype._handleSocketCloseBeforeAccept = function() {
+ this._socketIsClosing = true;
+ this._removeSocketCloseListeners();
+};
+
+WebSocketRequest.prototype._removeSocketCloseListeners = function() {
+ this.socket.removeListener('end', this._socketCloseHandler);
+ this.socket.removeListener('close', this._socketCloseHandler);
+};
+
+WebSocketRequest.prototype._verifyResolution = function() {
+ if (this._resolved) {
+ throw new Error('WebSocketRequest may only be accepted or rejected one time.');
+ }
+};
+
+function cleanupFailedConnection(connection) {
+ // Since we have to return a connection object even if the socket is
+ // already dead in order not to break the API, we schedule a 'close'
+ // event on the connection object to occur immediately.
+ process.nextTick(function() {
+ // WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006
+ // Third param: Skip sending the close frame to a dead socket
+ connection.drop(1006, 'TCP connection lost before handshake completed.', true);
+ });
+}
+
+module.exports = WebSocketRequest;
diff --git a/lib/WebSocketRouter.js b/lib/WebSocketRouter.js
new file mode 100644
index 0000000..35bced9
--- /dev/null
+++ b/lib/WebSocketRouter.js
@@ -0,0 +1,157 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var extend = require('./utils').extend;
+var util = require('util');
+var EventEmitter = require('events').EventEmitter;
+var WebSocketRouterRequest = require('./WebSocketRouterRequest');
+
+function WebSocketRouter(config) {
+ // Superclass Constructor
+ EventEmitter.call(this);
+
+ this.config = {
+ // The WebSocketServer instance to attach to.
+ server: null
+ };
+ if (config) {
+ extend(this.config, config);
+ }
+ this.handlers = [];
+
+ this._requestHandler = this.handleRequest.bind(this);
+ if (this.config.server) {
+ this.attachServer(this.config.server);
+ }
+}
+
+util.inherits(WebSocketRouter, EventEmitter);
+
+WebSocketRouter.prototype.attachServer = function(server) {
+ if (server) {
+ this.server = server;
+ this.server.on('request', this._requestHandler);
+ }
+ else {
+ throw new Error('You must specify a WebSocketServer instance to attach to.');
+ }
+};
+
+WebSocketRouter.prototype.detachServer = function() {
+ if (this.server) {
+ this.server.removeListener('request', this._requestHandler);
+ this.server = null;
+ }
+ else {
+ throw new Error('Cannot detach from server: not attached.');
+ }
+};
+
+WebSocketRouter.prototype.mount = function(path, protocol, callback) {
+ if (!path) {
+ throw new Error('You must specify a path for this handler.');
+ }
+ if (!protocol) {
+ protocol = '____no_protocol____';
+ }
+ if (!callback) {
+ throw new Error('You must specify a callback for this handler.');
+ }
+
+ path = this.pathToRegExp(path);
+ if (!(path instanceof RegExp)) {
+ throw new Error('Path must be specified as either a string or a RegExp.');
+ }
+ var pathString = path.toString();
+
+ // normalize protocol to lower-case
+ protocol = protocol.toLocaleLowerCase();
+
+ if (this.findHandlerIndex(pathString, protocol) !== -1) {
+ throw new Error('You may only mount one handler per path/protocol combination.');
+ }
+
+ this.handlers.push({
+ 'path': path,
+ 'pathString': pathString,
+ 'protocol': protocol,
+ 'callback': callback
+ });
+};
+WebSocketRouter.prototype.unmount = function(path, protocol) {
+ var index = this.findHandlerIndex(this.pathToRegExp(path).toString(), protocol);
+ if (index !== -1) {
+ this.handlers.splice(index, 1);
+ }
+ else {
+ throw new Error('Unable to find a route matching the specified path and protocol.');
+ }
+};
+
+WebSocketRouter.prototype.findHandlerIndex = function(pathString, protocol) {
+ protocol = protocol.toLocaleLowerCase();
+ for (var i=0, len=this.handlers.length; i < len; i++) {
+ var handler = this.handlers[i];
+ if (handler.pathString === pathString && handler.protocol === protocol) {
+ return i;
+ }
+ }
+ return -1;
+};
+
+WebSocketRouter.prototype.pathToRegExp = function(path) {
+ if (typeof(path) === 'string') {
+ if (path === '*') {
+ path = /^.*$/;
+ }
+ else {
+ path = path.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+ path = new RegExp('^' + path + '$');
+ }
+ }
+ return path;
+};
+
+WebSocketRouter.prototype.handleRequest = function(request) {
+ var requestedProtocols = request.requestedProtocols;
+ if (requestedProtocols.length === 0) {
+ requestedProtocols = ['____no_protocol____'];
+ }
+
+ // Find a handler with the first requested protocol first
+ for (var i=0; i < requestedProtocols.length; i++) {
+ var requestedProtocol = requestedProtocols[i].toLocaleLowerCase();
+
+ // find the first handler that can process this request
+ for (var j=0, len=this.handlers.length; j < len; j++) {
+ var handler = this.handlers[j];
+ if (handler.path.test(request.resourceURL.pathname)) {
+ if (requestedProtocol === handler.protocol ||
+ handler.protocol === '*')
+ {
+ var routerRequest = new WebSocketRouterRequest(request, requestedProtocol);
+ handler.callback(routerRequest);
+ return;
+ }
+ }
+ }
+ }
+
+ // If we get here we were unable to find a suitable handler.
+ request.reject(404, 'No handler is available for the given request.');
+};
+
+module.exports = WebSocketRouter;
diff --git a/lib/WebSocketRouterRequest.js b/lib/WebSocketRouterRequest.js
new file mode 100644
index 0000000..d3e3745
--- /dev/null
+++ b/lib/WebSocketRouterRequest.js
@@ -0,0 +1,54 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var util = require('util');
+var EventEmitter = require('events').EventEmitter;
+
+function WebSocketRouterRequest(webSocketRequest, resolvedProtocol) {
+ // Superclass Constructor
+ EventEmitter.call(this);
+
+ this.webSocketRequest = webSocketRequest;
+ if (resolvedProtocol === '____no_protocol____') {
+ this.protocol = null;
+ }
+ else {
+ this.protocol = resolvedProtocol;
+ }
+ this.origin = webSocketRequest.origin;
+ this.resource = webSocketRequest.resource;
+ this.resourceURL = webSocketRequest.resourceURL;
+ this.httpRequest = webSocketRequest.httpRequest;
+ this.remoteAddress = webSocketRequest.remoteAddress;
+ this.webSocketVersion = webSocketRequest.webSocketVersion;
+ this.requestedExtensions = webSocketRequest.requestedExtensions;
+ this.cookies = webSocketRequest.cookies;
+}
+
+util.inherits(WebSocketRouterRequest, EventEmitter);
+
+WebSocketRouterRequest.prototype.accept = function(origin, cookies) {
+ var connection = this.webSocketRequest.accept(this.protocol, origin, cookies);
+ this.emit('requestAccepted', connection);
+ return connection;
+};
+
+WebSocketRouterRequest.prototype.reject = function(status, reason, extraHeaders) {
+ this.webSocketRequest.reject(status, reason, extraHeaders);
+ this.emit('requestRejected', this);
+};
+
+module.exports = WebSocketRouterRequest;
diff --git a/lib/WebSocketServer.js b/lib/WebSocketServer.js
new file mode 100644
index 0000000..c27d967
--- /dev/null
+++ b/lib/WebSocketServer.js
@@ -0,0 +1,245 @@
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var extend = require('./utils').extend;
+var utils = require('./utils');
+var util = require('util');
+var debug = require('debug')('websocket:server');
+var EventEmitter = require('events').EventEmitter;
+var WebSocketRequest = require('./WebSocketRequest');
+
+var WebSocketServer = function WebSocketServer(config) {
+ // Superclass Constructor
+ EventEmitter.call(this);
+
+ this._handlers = {
+ upgrade: this.handleUpgrade.bind(this),
+ requestAccepted: this.handleRequestAccepted.bind(this),
+ requestResolved: this.handleRequestResolved.bind(this)
+ };
+ this.connections = [];
+ this.pendingRequests = [];
+ if (config) {
+ this.mount(config);
+ }
+};
+
+util.inherits(WebSocketServer, EventEmitter);
+
+WebSocketServer.prototype.mount = function(config) {
+ this.config = {
+ // The http server instance to attach to. Required.
+ httpServer: null,
+
+ // 64KiB max frame size.
+ maxReceivedFrameSize: 0x10000,
+
+ // 1MiB max message size, only applicable if
+ // assembleFragments is true
+ maxReceivedMessageSize: 0x100000,
+
+ // Outgoing messages larger than fragmentationThreshold will be
+ // split into multiple fragments.
+ fragmentOutgoingMessages: true,
+
+ // Outgoing frames are fragmented if they exceed this threshold.
+ // Default is 16KiB
+ fragmentationThreshold: 0x4000,
+
+ // If true, the server will automatically send a ping to all
+ // clients every 'keepaliveInterval' milliseconds. The timer is
+ // reset on any received data from the client.
+ keepalive: true,
+
+ // The interval to send keepalive pings to connected clients if the
+ // connection is idle. Any received data will reset the counter.
+ keepaliveInterval: 20000,
+
+ // If true, the server will consider any connection that has not
+ // received any data within the amount of time specified by
+ // 'keepaliveGracePeriod' after a keepalive ping has been sent to
+ // be dead, and will drop the connection.
+ // Ignored if keepalive is false.
+ dropConnectionOnKeepaliveTimeout: true,
+
+ // The amount of time to wait after sending a keepalive ping before
+ // closing the connection if the connected peer does not respond.
+ // Ignored if keepalive is false.
+ keepaliveGracePeriod: 10000,
+
+ // Whether to use native TCP keep-alive instead of WebSockets ping
+ // and pong packets. Native TCP keep-alive sends smaller packets
+ // on the wire and so uses bandwidth more efficiently. This may
+ // be more important when talking to mobile devices.
+ // If this value is set to true, then these values will be ignored:
+ // keepaliveGracePeriod
+ // dropConnectionOnKeepaliveTimeout
+ useNativeKeepalive: false,
+
+ // If true, fragmented messages will be automatically assembled
+ // and the full message will be emitted via a 'message' event.
+ // If false, each frame will be emitted via a 'frame' event and
+ // the application will be responsible for aggregating multiple
+ // fragmented frames. Single-frame messages will emit a 'message'
+ // event in addition to the 'frame' event.
+ // Most users will want to leave this set to 'true'
+ assembleFragments: true,
+
+ // If this is true, websocket connections will be accepted
+ // regardless of the path and protocol specified by the client.
+ // The protocol accepted will be the first that was requested
+ // by the client. Clients from any origin will be accepted.
+ // This should only be used in the simplest of cases. You should
+ // probably leave this set to 'false' and inspect the request
+ // object to make sure it's acceptable before accepting it.
+ autoAcceptConnections: false,
+
+ // Whether or not the X-Forwarded-For header should be respected.
+ // It's important to set this to 'true' when accepting connections
+ // from untrusted clients, as a malicious client could spoof its
+ // IP address by simply setting this header. It's meant to be added
+ // by a trusted proxy or other intermediary within your own
+ // infrastructure.
+ // See: http://en.wikipedia.org/wiki/X-Forwarded-For
+ ignoreXForwardedFor: false,
+
+ // The Nagle Algorithm makes more efficient use of network resources
+ // by introducing a small delay before sending small packets so that
+ // multiple messages can be batched together before going onto the
+ // wire. This however comes at the cost of latency, so the default
+ // is to disable it. If you don't need low latency and are streaming
+ // lots of small messages, you can change this to 'false'
+ disableNagleAlgorithm: true,
+
+ // The number of milliseconds to wait after sending a close frame
+ // for an acknowledgement to come back before giving up and just
+ // closing the socket.
+ closeTimeout: 5000
+ };
+ extend(this.config, config);
+
+ if (this.config.httpServer) {
+ if (!Array.isArray(this.config.httpServer)) {
+ this.config.httpServer = [this.config.httpServer];
+ }
+ var upgradeHandler = this._handlers.upgrade;
+ this.config.httpServer.forEach(function(httpServer) {
+ httpServer.on('upgrade', upgradeHandler);
+ });
+ }
+ else {
+ throw new Error('You must specify an httpServer on which to mount the WebSocket server.');
+ }
+};
+
+WebSocketServer.prototype.unmount = function() {
+ var upgradeHandler = this._handlers.upgrade;
+ this.config.httpServer.forEach(function(httpServer) {
+ httpServer.removeListener('upgrade', upgradeHandler);
+ });
+};
+
+WebSocketServer.prototype.closeAllConnections = function() {
+ this.connections.forEach(function(connection) {
+ connection.close();
+ });
+ this.pendingRequests.forEach(function(request) {
+ process.nextTick(function() {
+ request.reject(503); // HTTP 503 Service Unavailable
+ });
+ });
+};
+
+WebSocketServer.prototype.broadcast = function(data) {
+ if (Buffer.isBuffer(data)) {
+ this.broadcastBytes(data);
+ }
+ else if (typeof(data.toString) === 'function') {
+ this.broadcastUTF(data);
+ }
+};
+
+WebSocketServer.prototype.broadcastUTF = function(utfData) {
+ this.connections.forEach(function(connection) {
+ connection.sendUTF(utfData);
+ });
+};
+
+WebSocketServer.prototype.broadcastBytes = function(binaryData) {
+ this.connections.forEach(function(connection) {
+ connection.sendBytes(binaryData);
+ });
+};
+
+WebSocketServer.prototype.shutDown = function() {
+ this.unmount();
+ this.closeAllConnections();
+};
+
+WebSocketServer.prototype.handleUpgrade = function(request, socket) {
+ var wsRequest = new WebSocketRequest(socket, request, this.config);
+ try {
+ wsRequest.readHandshake();
+ }
+ catch(e) {
+ wsRequest.reject(
+ e.httpCode ? e.httpCode : 400,
+ e.message,
+ e.headers
+ );
+ debug('Invalid handshake: %s', e.message);
+ return;
+ }
+
+ this.pendingRequests.push(wsRequest);
+
+ wsRequest.once('requestAccepted', this._handlers.requestAccepted);
+ wsRequest.once('requestResolved', this._handlers.requestResolved);
+
+ if (!this.config.autoAcceptConnections && utils.eventEmitterListenerCount(this, 'request') > 0) {
+ this.emit('request', wsRequest);
+ }
+ else if (this.config.autoAcceptConnections) {
+ wsRequest.accept(wsRequest.requestedProtocols[0], wsRequest.origin);
+ }
+ else {
+ wsRequest.reject(404, 'No handler is configured to accept the connection.');
+ }
+};
+
+WebSocketServer.prototype.handleRequestAccepted = function(connection) {
+ var self = this;
+ connection.once('close', function(closeReason, description) {
+ self.handleConnectionClose(connection, closeReason, description);
+ });
+ this.connections.push(connection);
+ this.emit('connect', connection);
+};
+
+WebSocketServer.prototype.handleConnectionClose = function(connection, closeReason, description) {
+ var index = this.connections.indexOf(connection);
+ if (index !== -1) {
+ this.connections.splice(index, 1);
+ }
+ this.emit('close', connection, closeReason, description);
+};
+
+WebSocketServer.prototype.handleRequestResolved = function(request) {
+ var index = this.pendingRequests.indexOf(request);
+ if (index !== -1) { this.pendingRequests.splice(index, 1); }
+};
+
+module.exports = WebSocketServer;
diff --git a/lib/browser.js b/lib/browser.js
new file mode 100644
index 0000000..16c641b
--- /dev/null
+++ b/lib/browser.js
@@ -0,0 +1,36 @@
+var _global = (function() { return this; })();
+var nativeWebSocket = _global.WebSocket || _global.MozWebSocket;
+var websocket_version = require('./version');
+
+
+/**
+ * Expose a W3C WebSocket class with just one or two arguments.
+ */
+function W3CWebSocket(uri, protocols) {
+ var native_instance;
+
+ if (protocols) {
+ native_instance = new nativeWebSocket(uri, protocols);
+ }
+ else {
+ native_instance = new nativeWebSocket(uri);
+ }
+
+ /**
+ * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket
+ * class). Since it is an Object it will be returned as it is when creating an
+ * instance of W3CWebSocket via 'new W3CWebSocket()'.
+ *
+ * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2
+ */
+ return native_instance;
+}
+
+
+/**
+ * Module exports.
+ */
+module.exports = {
+ 'w3cwebsocket' : nativeWebSocket ? W3CWebSocket : null,
+ 'version' : websocket_version
+};
diff --git a/lib/utils.js b/lib/utils.js
new file mode 100644
index 0000000..6506dc9
--- /dev/null
+++ b/lib/utils.js
@@ -0,0 +1,60 @@
+var noop = exports.noop = function(){};
+
+exports.extend = function extend(dest, source) {
+ for (var prop in source) {
+ dest[prop] = source[prop];
+ }
+};
+
+exports.eventEmitterListenerCount =
+ require('events').EventEmitter.listenerCount ||
+ function(emitter, type) { return emitter.listeners(type).length; };
+
+
+
+
+
+exports.BufferingLogger = function createBufferingLogger(identifier, uniqueID) {
+ var logFunction = require('debug')(identifier);
+ if (logFunction.enabled) {
+ var logger = new BufferingLogger(identifier, uniqueID, logFunction);
+ var debug = logger.log.bind(logger);
+ debug.printOutput = logger.printOutput.bind(logger);
+ debug.enabled = logFunction.enabled;
+ return debug;
+ }
+ logFunction.printOutput = noop;
+ return logFunction;
+};
+
+function BufferingLogger(identifier, uniqueID, logFunction) {
+ this.logFunction = logFunction;
+ this.identifier = identifier;
+ this.uniqueID = uniqueID;
+ this.buffer = [];
+}
+
+BufferingLogger.prototype.log = function() {
+ this.buffer.push([ new Date(), Array.prototype.slice.call(arguments) ]);
+ return this;
+};
+
+BufferingLogger.prototype.clear = function() {
+ this.buffer = [];
+ return this;
+};
+
+BufferingLogger.prototype.printOutput = function(logFunction) {
+ if (!logFunction) { logFunction = this.logFunction; }
+ var uniqueID = this.uniqueID;
+ this.buffer.forEach(function(entry) {
+ var date = entry[0].toLocaleString();
+ var args = entry[1].slice();
+ var formatString = args[0];
+ if (formatString !== (void 0) && formatString !== null) {
+ formatString = '%s - %s - ' + formatString.toString();
+ args.splice(0, 1, formatString, date, uniqueID);
+ logFunction.apply(global, args);
+ }
+ });
+};
diff --git a/lib/version.js b/lib/version.js
new file mode 100644
index 0000000..81f6e78
--- /dev/null
+++ b/lib/version.js
@@ -0,0 +1 @@
+module.exports = require('../package.json').version;
diff --git a/lib/websocket.js b/lib/websocket.js
new file mode 100644
index 0000000..6242d56
--- /dev/null
+++ b/lib/websocket.js
@@ -0,0 +1,11 @@
+module.exports = {
+ 'server' : require('./WebSocketServer'),
+ 'client' : require('./WebSocketClient'),
+ 'router' : require('./WebSocketRouter'),
+ 'frame' : require('./WebSocketFrame'),
+ 'request' : require('./WebSocketRequest'),
+ 'connection' : require('./WebSocketConnection'),
+ 'w3cwebsocket' : require('./W3CWebSocket'),
+ 'deprecation' : require('./Deprecation'),
+ 'version' : require('./version')
+};
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..98e07c9
--- /dev/null
+++ b/package.json
@@ -0,0 +1,57 @@
+{
+ "name": "websocket",
+ "description": "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.",
+ "keywords": [
+ "websocket",
+ "websockets",
+ "socket",
+ "networking",
+ "comet",
+ "push",
+ "RFC-6455",
+ "realtime",
+ "server",
+ "client"
+ ],
+ "author": "Brian McKelvey <brian@worlize.com> (https://www.worlize.com/)",
+ "contributors": [
+ "Iñaki Baz Castillo <ibc@aliax.net> (http://dev.sipdoc.net)"
+ ],
+ "version": "1.0.23",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/theturtle32/WebSocket-Node.git"
+ },
+ "homepage": "https://github.com/theturtle32/WebSocket-Node",
+ "engines": {
+ "node": ">=0.8.0"
+ },
+ "dependencies": {
+ "debug": "^2.2.0",
+ "nan": "^2.3.3",
+ "typedarray-to-buffer": "^3.1.2",
+ "yaeti": "^0.0.4"
+ },
+ "devDependencies": {
+ "buffer-equal": "^0.0.1",
+ "faucet": "^0.0.1",
+ "gulp": "git+https://github.com/gulpjs/gulp.git#4.0",
+ "gulp-jshint": "^1.11.2",
+ "jshint-stylish": "^1.0.2",
+ "tape": "^4.0.1"
+ },
+ "config": {
+ "verbose": false
+ },
+ "scripts": {
+ "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)",
+ "test": "faucet test/unit",
+ "gulp": "gulp"
+ },
+ "main": "index",
+ "directories": {
+ "lib": "./lib"
+ },
+ "browser": "lib/browser.js",
+ "license": "Apache-2.0"
+}
diff --git a/src/bufferutil.cc b/src/bufferutil.cc
new file mode 100644
index 0000000..d2f8d2d
--- /dev/null
+++ b/src/bufferutil.cc
@@ -0,0 +1,121 @@
+/*!
+ * BufferUtil originally from:
+ * ws: a node.js websocket client
+ * Copyright(c) 2015 Einar Otto Stangvik <einaros@gmail.com>
+ * MIT Licensed
+ */
+
+#include <v8.h>
+#include <node.h>
+#include <node_version.h>
+#include <node_buffer.h>
+#include <node_object_wrap.h>
+#include <stdlib.h>
+#include <string.h>
+#include <wchar.h>
+#include <stdio.h>
+#include "nan.h"
+
+using namespace v8;
+using namespace node;
+
+class BufferUtil : public ObjectWrap
+{
+public:
+
+ static void Initialize(v8::Handle<v8::Object> target)
+ {
+ Nan::HandleScope scope;
+ Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
+ t->InstanceTemplate()->SetInternalFieldCount(1);
+ Nan::SetMethod(t, "unmask", BufferUtil::Unmask);
+ Nan::SetMethod(t, "mask", BufferUtil::Mask);
+ Nan::SetMethod(t, "merge", BufferUtil::Merge);
+ Nan::Set(target, Nan::New<String>("BufferUtil").ToLocalChecked(), t->GetFunction());
+ }
+
+protected:
+
+ static NAN_METHOD(New)
+ {
+ Nan::HandleScope scope;
+ BufferUtil* bufferUtil = new BufferUtil();
+ bufferUtil->Wrap(info.This());
+ info.GetReturnValue().Set(info.This());
+ }
+
+ static NAN_METHOD(Merge)
+ {
+ Nan::HandleScope scope;
+ Local<Object> bufferObj = info[0]->ToObject();
+ char* buffer = Buffer::Data(bufferObj);
+ Local<Array> array = Local<Array>::Cast(info[1]);
+ unsigned int arrayLength = array->Length();
+ size_t offset = 0;
+ unsigned int i;
+ for (i = 0; i < arrayLength; ++i) {
+ Local<Object> src = array->Get(i)->ToObject();
+ size_t length = Buffer::Length(src);
+ memcpy(buffer + offset, Buffer::Data(src), length);
+ offset += length;
+ }
+ info.GetReturnValue().Set(Nan::True());
+ }
+
+ static NAN_METHOD(Unmask)
+ {
+ Nan::HandleScope scope;
+ Local<Object> buffer_obj = info[0]->ToObject();
+ size_t length = Buffer::Length(buffer_obj);
+ Local<Object> mask_obj = info[1]->ToObject();
+ unsigned int *mask = (unsigned int*)Buffer::Data(mask_obj);
+ unsigned int* from = (unsigned int*)Buffer::Data(buffer_obj);
+ size_t len32 = length / 4;
+ unsigned int i;
+ for (i = 0; i < len32; ++i) *(from + i) ^= *mask;
+ from += i;
+ switch (length % 4) {
+ case 3: *((unsigned char*)from+2) = *((unsigned char*)from+2) ^ ((unsigned char*)mask)[2];
+ case 2: *((unsigned char*)from+1) = *((unsigned char*)from+1) ^ ((unsigned char*)mask)[1];
+ case 1: *((unsigned char*)from ) = *((unsigned char*)from ) ^ ((unsigned char*)mask)[0];
+ case 0:;
+ }
+ info.GetReturnValue().Set(Nan::True());
+ }
+
+ static NAN_METHOD(Mask)
+ {
+ Nan::HandleScope scope;
+ Local<Object> buffer_obj = info[0]->ToObject();
+ Local<Object> mask_obj = info[1]->ToObject();
+ unsigned int *mask = (unsigned int*)Buffer::Data(mask_obj);
+ Local<Object> output_obj = info[2]->ToObject();
+ unsigned int dataOffset = info[3]->Int32Value();
+ unsigned int length = info[4]->Int32Value();
+ unsigned int* to = (unsigned int*)(Buffer::Data(output_obj) + dataOffset);
+ unsigned int* from = (unsigned int*)Buffer::Data(buffer_obj);
+ unsigned int len32 = length / 4;
+ unsigned int i;
+ for (i = 0; i < len32; ++i) *(to + i) = *(from + i) ^ *mask;
+ to += i;
+ from += i;
+ switch (length % 4) {
+ case 3: *((unsigned char*)to+2) = *((unsigned char*)from+2) ^ *((unsigned char*)mask+2);
+ case 2: *((unsigned char*)to+1) = *((unsigned char*)from+1) ^ *((unsigned char*)mask+1);
+ case 1: *((unsigned char*)to ) = *((unsigned char*)from ) ^ *((unsigned char*)mask);
+ case 0:;
+ }
+ info.GetReturnValue().Set(Nan::True());
+ }
+};
+
+#if !NODE_VERSION_AT_LEAST(0,10,0)
+extern "C"
+#endif
+void init (Handle<Object> target)
+{
+ Nan::HandleScope scope;
+ BufferUtil::Initialize(target);
+}
+
+NODE_MODULE(bufferutil, init)
diff --git a/src/validation.cc b/src/validation.cc
new file mode 100644
index 0000000..8e2347e
--- /dev/null
+++ b/src/validation.cc
@@ -0,0 +1,148 @@
+/*!
+ * UTF-8 Validation Code originally from:
+ * ws: a node.js websocket client
+ * Copyright(c) 2015 Einar Otto Stangvik <einaros@gmail.com>
+ * MIT Licensed
+ */
+
+#include <v8.h>
+#include <node.h>
+#include <node_version.h>
+#include <node_buffer.h>
+#include <node_object_wrap.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <stdio.h>
+#include "nan.h"
+
+using namespace v8;
+using namespace node;
+
+#define UNI_SUR_HIGH_START (uint32_t) 0xD800
+#define UNI_SUR_LOW_END (uint32_t) 0xDFFF
+#define UNI_REPLACEMENT_CHAR (uint32_t) 0x0000FFFD
+#define UNI_MAX_LEGAL_UTF32 (uint32_t) 0x0010FFFF
+
+static const uint8_t trailingBytesForUTF8[256] = {
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
+};
+
+static const uint32_t offsetsFromUTF8[6] = {
+ 0x00000000, 0x00003080, 0x000E2080,
+ 0x03C82080, 0xFA082080, 0x82082080
+};
+
+static int isLegalUTF8(const uint8_t *source, const int length)
+{
+ uint8_t a;
+ const uint8_t *srcptr = source+length;
+ switch (length) {
+ default: return 0;
+ /* Everything else falls through when "true"... */
+ /* RFC3629 makes 5 & 6 bytes UTF-8 illegal
+ case 6: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0;
+ case 5: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; */
+ case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0;
+ case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0;
+ case 2: if ((a = (*--srcptr)) > 0xBF) return 0;
+ switch (*source) {
+ /* no fall-through in this inner switch */
+ case 0xE0: if (a < 0xA0) return 0; break;
+ case 0xED: if (a > 0x9F) return 0; break;
+ case 0xF0: if (a < 0x90) return 0; break;
+ case 0xF4: if (a > 0x8F) return 0; break;
+ default: if (a < 0x80) return 0;
+ }
+
+ case 1: if (*source >= 0x80 && *source < 0xC2) return 0;
+ }
+ if (*source > 0xF4) return 0;
+ return 1;
+}
+
+int is_valid_utf8 (size_t len, char *value)
+{
+ /* is the string valid UTF-8? */
+ for (unsigned int i = 0; i < len; i++) {
+ uint32_t ch = 0;
+ uint8_t extrabytes = trailingBytesForUTF8[(uint8_t) value[i]];
+
+ if (extrabytes + i >= len)
+ return 0;
+
+ if (isLegalUTF8 ((uint8_t *) (value + i), extrabytes + 1) == 0) return 0;
+
+ switch (extrabytes) {
+ case 5 : ch += (uint8_t) value[i++]; ch <<= 6;
+ case 4 : ch += (uint8_t) value[i++]; ch <<= 6;
+ case 3 : ch += (uint8_t) value[i++]; ch <<= 6;
+ case 2 : ch += (uint8_t) value[i++]; ch <<= 6;
+ case 1 : ch += (uint8_t) value[i++]; ch <<= 6;
+ case 0 : ch += (uint8_t) value[i];
+ }
+
+ ch -= offsetsFromUTF8[extrabytes];
+
+ if (ch <= UNI_MAX_LEGAL_UTF32) {
+ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END)
+ return 0;
+ } else {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+class Validation : public ObjectWrap
+{
+public:
+
+ static void Initialize(v8::Handle<v8::Object> target)
+ {
+ Nan::HandleScope scope;
+ Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);
+ t->InstanceTemplate()->SetInternalFieldCount(1);
+ Nan::SetMethod(t, "isValidUTF8", Validation::IsValidUTF8);
+ Nan::Set(target, Nan::New<String>("Validation").ToLocalChecked(), t->GetFunction());
+ }
+
+protected:
+
+ static NAN_METHOD(New)
+ {
+ Nan::HandleScope scope;
+ Validation* validation = new Validation();
+ validation->Wrap(info.This());
+ info.GetReturnValue().Set(info.This());
+ }
+
+ static NAN_METHOD(IsValidUTF8)
+ {
+ Nan::HandleScope scope;
+ if (!Buffer::HasInstance(info[0])) {
+ return Nan::ThrowTypeError("First argument needs to be a buffer");
+ }
+ Local<Object> buffer_obj = info[0]->ToObject();
+ char *buffer_data = Buffer::Data(buffer_obj);
+ size_t buffer_length = Buffer::Length(buffer_obj);
+ info.GetReturnValue().Set(is_valid_utf8(buffer_length, buffer_data) == 1 ? Nan::True() : Nan::False());
+ }
+};
+#if !NODE_VERSION_AT_LEAST(0,10,0)
+extern "C"
+#endif
+void init (Handle<Object> target)
+{
+ Nan::HandleScope scope;
+ Validation::Initialize(target);
+}
+
+NODE_MODULE(validation, init)
diff --git a/test/autobahn/fuzzingclient.json b/test/autobahn/fuzzingclient.json
new file mode 100644
index 0000000..6a8ec66
--- /dev/null
+++ b/test/autobahn/fuzzingclient.json
@@ -0,0 +1,17 @@
+
+{
+ "options": {"failByDrop": false},
+ "outdir": "./reports/servers",
+
+ "servers": [
+ {
+ "agent": "WebSocket-Node 1.0.23",
+ "url": "ws://127.0.0.1:8080",
+ "options": {"version": 18}
+ }
+ ],
+
+ "cases": ["*"],
+ "exclude-cases": [],
+ "exclude-agent-cases": {}
+}
diff --git a/test/scripts/autobahn-test-client.js b/test/scripts/autobahn-test-client.js
new file mode 100755
index 0000000..74bb95d
--- /dev/null
+++ b/test/scripts/autobahn-test-client.js
@@ -0,0 +1,135 @@
+#!/usr/bin/env node
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the 'License');
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an 'AS IS' BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var WebSocketClient = require('../../lib/WebSocketClient');
+var wsVersion = require('../../lib/websocket').version;
+var querystring = require('querystring');
+
+var args = { /* defaults */
+ secure: false,
+ port: '9000',
+ host: 'localhost'
+};
+
+/* Parse command line options */
+var pattern = /^--(.*?)(?:=(.*))?$/;
+process.argv.forEach(function(value) {
+ var match = pattern.exec(value);
+ if (match) {
+ args[match[1]] = match[2] ? match[2] : true;
+ }
+});
+
+args.protocol = args.secure ? 'wss:' : 'ws:';
+
+console.log('WebSocket-Node: Echo test client for running against the Autobahn test suite');
+console.log('Usage: ./libwebsockets-test-client.js --host=127.0.0.1 --port=9000 [--secure]');
+console.log('');
+
+
+console.log('Starting test run.');
+
+getCaseCount(function(caseCount) {
+ var currentCase = 1;
+ runNextTestCase();
+
+ function runNextTestCase() {
+ runTestCase(currentCase++, caseCount, function() {
+ if (currentCase <= caseCount) {
+ process.nextTick(runNextTestCase);
+ }
+ else {
+ process.nextTick(function() {
+ console.log('Test suite complete, generating report.');
+ updateReport(function() {
+ console.log('Report generated.');
+ });
+ });
+ }
+ });
+ }
+});
+
+
+function runTestCase(caseIndex, caseCount, callback) {
+ console.log('Running test ' + caseIndex + ' of ' + caseCount);
+ var echoClient = new WebSocketClient({
+ maxReceivedFrameSize: 64*1024*1024, // 64MiB
+ maxReceivedMessageSize: 64*1024*1024, // 64MiB
+ fragmentOutgoingMessages: false,
+ keepalive: false,
+ disableNagleAlgorithm: false
+ });
+
+ echoClient.on('connectFailed', function(error) {
+ console.log('Connect Error: ' + error.toString());
+ });
+
+ echoClient.on('connect', function(connection) {
+ connection.on('error', function(error) {
+ console.log('Connection Error: ' + error.toString());
+ });
+ connection.on('close', function() {
+ callback();
+ });
+ connection.on('message', function(message) {
+ if (message.type === 'utf8') {
+ connection.sendUTF(message.utf8Data);
+ }
+ else if (message.type === 'binary') {
+ connection.sendBytes(message.binaryData);
+ }
+ });
+ });
+
+ var qs = querystring.stringify({
+ case: caseIndex,
+ agent: 'WebSocket-Node Client v' + wsVersion
+ });
+ echoClient.connect('ws://' + args.host + ':' + args.port + '/runCase?' + qs, []);
+}
+
+function getCaseCount(callback) {
+ var client = new WebSocketClient();
+ var caseCount = NaN;
+ client.on('connect', function(connection) {
+ connection.on('close', function() {
+ callback(caseCount);
+ });
+ connection.on('message', function(message) {
+ if (message.type === 'utf8') {
+ console.log('Got case count: ' + message.utf8Data);
+ caseCount = parseInt(message.utf8Data, 10);
+ }
+ else if (message.type === 'binary') {
+ throw new Error('Unexpected binary message when retrieving case count');
+ }
+ });
+ });
+ client.connect('ws://' + args.host + ':' + args.port + '/getCaseCount', []);
+}
+
+function updateReport(callback) {
+ var client = new WebSocketClient();
+ var qs = querystring.stringify({
+ agent: 'WebSocket-Node Client v' + wsVersion
+ });
+ client.on('connect', function(connection) {
+ connection.on('close', callback);
+ });
+ client.connect('ws://localhost:9000/updateReports?' + qs);
+}
diff --git a/test/scripts/certificate.pem b/test/scripts/certificate.pem
new file mode 100644
index 0000000..0018001
--- /dev/null
+++ b/test/scripts/certificate.pem
@@ -0,0 +1,15 @@
+-----BEGIN CERTIFICATE-----
+MIICSzCCAbQCCQC5xbEo0fggtTANBgkqhkiG9w0BAQUFADBqMQswCQYDVQQGEwJV
+UzETMBEGA1UECBMKQ2FsaWZvcm5pYTEUMBIGA1UEBxMLTG9zIEFuZ2VsZXMxDTAL
+BgNVBAoTBE5vbmUxDTALBgNVBAsTBE5vbmUxEjAQBgNVBAMTCWxvY2FsaG9zdDAe
+Fw0xNDEwMTkyMzM5MDJaFw0xNDExMTgyMzM5MDJaMGoxCzAJBgNVBAYTAlVTMRMw
+EQYDVQQIEwpDYWxpZm9ybmlhMRQwEgYDVQQHEwtMb3MgQW5nZWxlczENMAsGA1UE
+ChMETm9uZTENMAsGA1UECxMETm9uZTESMBAGA1UEAxMJbG9jYWxob3N0MIGfMA0G
+CSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpX8/M7iA86+s0N91CRj1e83LEuJ48M6Mr
+CJBosYYWKz983sw0Kf1QviW5dhAzT5R1AdGyvddVd80z5J9tNZqje2vyrXssClq+
+iETxW8U71wfUZ/VmGhWcXwU7XD4JP33WbTIEHS2xgpMQNXQnQFM40+NjQBViK0b9
+mQtclOliqwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAAyGak0l7boxJzJBYSw1CyaV
+Ibs9nnSW3HqhsEml+rPp+7+0G6wUYcMolPCUY13K4aIG0n7c6oDwvtcWWbjnVxAb
+i2wBL35mByrbZKiOoQTpCPsFE7fNK3vnvkXkhvTrAkX5vscug0XDwpl0rz5X8lC1
+/V6Bu4GqNme6p2UVcRIH
+-----END CERTIFICATE-----
diff --git a/test/scripts/echo-server.js b/test/scripts/echo-server.js
new file mode 100755
index 0000000..75a3348
--- /dev/null
+++ b/test/scripts/echo-server.js
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the 'License');
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an 'AS IS' BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var WebSocketServer = require('../../lib/WebSocketServer');
+var http = require('http');
+
+var args = { /* defaults */
+ port: '8080',
+ debug: false
+};
+
+/* Parse command line options */
+var pattern = /^--(.*?)(?:=(.*))?$/;
+process.argv.forEach(function(value) {
+ var match = pattern.exec(value);
+ if (match) {
+ args[match[1]] = match[2] ? match[2] : true;
+ }
+});
+
+var port = parseInt(args.port, 10);
+var debug = args.debug;
+
+console.log('WebSocket-Node: echo-server');
+console.log('Usage: ./echo-server.js [--port=8080] [--debug]');
+
+var server = http.createServer(function(request, response) {
+ if (debug) { console.log((new Date()) + ' Received request for ' + request.url); }
+ response.writeHead(404);
+ response.end();
+});
+server.listen(port, function() {
+ console.log((new Date()) + ' Server is listening on port ' + port);
+});
+
+var wsServer = new WebSocketServer({
+ httpServer: server,
+ autoAcceptConnections: true,
+ maxReceivedFrameSize: 64*1024*1024, // 64MiB
+ maxReceivedMessageSize: 64*1024*1024, // 64MiB
+ fragmentOutgoingMessages: false,
+ keepalive: false,
+ disableNagleAlgorithm: false
+});
+
+wsServer.on('connect', function(connection) {
+ if (debug) { console.log((new Date()) + ' Connection accepted' +
+ ' - Protocol Version ' + connection.webSocketVersion); }
+ function sendCallback(err) {
+ if (err) {
+ console.error('send() error: ' + err);
+ connection.drop();
+ setTimeout(function() {
+ process.exit(100);
+ }, 100);
+ }
+ }
+ connection.on('message', function(message) {
+ if (message.type === 'utf8') {
+ if (debug) { console.log('Received utf-8 message of ' + message.utf8Data.length + ' characters.'); }
+ connection.sendUTF(message.utf8Data, sendCallback);
+ }
+ else if (message.type === 'binary') {
+ if (debug) { console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); }
+ connection.sendBytes(message.binaryData, sendCallback);
+ }
+ });
+ connection.on('close', function(reasonCode, description) {
+ if (debug) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }
+ connection._debug.printOutput();
+ });
+});
diff --git a/test/scripts/fragmentation-test-client.js b/test/scripts/fragmentation-test-client.js
new file mode 100755
index 0000000..0958ed7
--- /dev/null
+++ b/test/scripts/fragmentation-test-client.js
@@ -0,0 +1,163 @@
+#!/usr/bin/env node
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the 'License');
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an 'AS IS' BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var WebSocketClient = require('../../lib/WebSocketClient');
+
+console.log('WebSocket-Node: Test client for parsing fragmented messages.');
+
+var args = { /* defaults */
+ secure: false,
+ port: '8080',
+ host: '127.0.0.1',
+ 'no-defragment': false,
+ binary: false
+};
+
+/* Parse command line options */
+var pattern = /^--(.*?)(?:=(.*))?$/;
+process.argv.forEach(function(value) {
+ var match = pattern.exec(value);
+ if (match) {
+ args[match[1]] = match[2] ? match[2] : true;
+ }
+});
+
+args.protocol = args.secure ? 'wss:' : 'ws:';
+
+if (args.help) {
+ console.log('Usage: ./fragmentation-test-client.js [--host=127.0.0.1] [--port=8080] [--no-defragment] [--binary]');
+ console.log('');
+ return;
+}
+else {
+ console.log('Use --help for usage information.');
+}
+
+
+var client = new WebSocketClient({
+ maxReceivedMessageSize: 128*1024*1024, // 128 MiB
+ maxReceivedFrameSize: 1*1024*1024, // 1 MiB
+ assembleFragments: !args['no-defragment']
+});
+
+client.on('connectFailed', function(error) {
+ console.log('Client Error: ' + error.toString());
+});
+
+
+var requestedLength = 100;
+var messageSize = 0;
+var startTime;
+var byteCounter;
+
+client.on('connect', function(connection) {
+ console.log('Connected');
+ startTime = new Date();
+ byteCounter = 0;
+
+ connection.on('error', function(error) {
+ console.log('Connection Error: ' + error.toString());
+ });
+
+ connection.on('close', function() {
+ console.log('Connection Closed');
+ });
+
+ connection.on('message', function(message) {
+ if (message.type === 'utf8') {
+ console.log('Received utf-8 message of ' + message.utf8Data.length + ' characters.');
+ logThroughput(message.utf8Data.length);
+ requestData();
+ }
+ else {
+ console.log('Received binary message of ' + message.binaryData.length + ' bytes.');
+ logThroughput(message.binaryData.length);
+ requestData();
+ }
+ });
+
+ connection.on('frame', function(frame) {
+ console.log('Frame: 0x' + frame.opcode.toString(16) + '; ' + frame.length + ' bytes; Flags: ' + renderFlags(frame));
+ messageSize += frame.length;
+ if (frame.fin) {
+ console.log('Total message size: ' + messageSize + ' bytes.');
+ logThroughput(messageSize);
+ messageSize = 0;
+ requestData();
+ }
+ });
+
+ function logThroughput(numBytes) {
+ byteCounter += numBytes;
+ var duration = (new Date()).valueOf() - startTime.valueOf();
+ if (duration > 1000) {
+ var kiloBytesPerSecond = Math.round((byteCounter / 1024) / (duration/1000));
+ console.log(' Throughput: ' + kiloBytesPerSecond + ' KBps');
+ startTime = new Date();
+ byteCounter = 0;
+ }
+ }
+
+ function sendUTFCallback(err) {
+ if (err) { console.error('sendUTF() error: ' + err); }
+ }
+
+ function requestData() {
+ if (args.binary) {
+ connection.sendUTF('sendBinaryMessage|' + requestedLength, sendUTFCallback);
+ }
+ else {
+ connection.sendUTF('sendMessage|' + requestedLength, sendUTFCallback);
+ }
+ requestedLength += Math.ceil(Math.random() * 1024);
+ }
+
+ function renderFlags(frame) {
+ var flags = [];
+ if (frame.fin) {
+ flags.push('[FIN]');
+ }
+ if (frame.rsv1) {
+ flags.push('[RSV1]');
+ }
+ if (frame.rsv2) {
+ flags.push('[RSV2]');
+ }
+ if (frame.rsv3) {
+ flags.push('[RSV3]');
+ }
+ if (frame.mask) {
+ flags.push('[MASK]');
+ }
+ if (flags.length === 0) {
+ return '---';
+ }
+ return flags.join(' ');
+ }
+
+ requestData();
+});
+
+if (args['no-defragment']) {
+ console.log('Not automatically re-assembling fragmented messages.');
+}
+else {
+ console.log('Maximum aggregate message size: ' + client.config.maxReceivedMessageSize + ' bytes.');
+}
+console.log('Connecting');
+
+client.connect(args.protocol + '//' + args.host + ':' + args.port + '/', 'fragmentation-test');
diff --git a/test/scripts/fragmentation-test-page.html b/test/scripts/fragmentation-test-page.html
new file mode 100644
index 0000000..d60f6a6
--- /dev/null
+++ b/test/scripts/fragmentation-test-page.html
@@ -0,0 +1,121 @@
+<!DOCTYPE html>
+<html>
+<!--
+ Copyright 2010-2015 Brian McKelvey.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<head>
+ <meta charset="utf-8">
+ <title>Firefox Bug</title>
+ <script>
+
+ var socket;
+
+ var requestedLength;
+
+ function connect() {
+ if (socket && socket.readyState === WebSocket.OPEN) {
+ socket.close();
+ }
+ socket = new WebSocket(get_appropriate_ws_url(), 'fragmentation-test');
+ socket.onopen = handleSocketOpen;
+ socket.onmessage = handleSocketMessage;
+ socket.onclose = handleSocketClose;
+ socket.onerror = handleSocketError;
+ }
+
+ function disconnect() {
+ socket.close();
+ }
+
+ function clearLog() {
+
+ }
+
+ function clearLog() {
+ var el = document.getElementById('output');
+ el.innerHTML = '';
+ }
+
+ function log(data) {
+ // if (window['console'] && window['console']['log'])
+ // console.log(data)
+
+ var el = document.getElementById('output');
+ el.innerHTML += ('<br>\n' + data);
+ }
+
+ function requestData() {
+ socket.send('sendMessage|' + requestedLength);
+ requestedLength += Math.ceil(Math.random() * 1024);
+ }
+
+ function handleSocketOpen() {
+ log("Socket opened.");
+ requestedLength = 100;
+ requestData();
+ }
+
+ function handleSocketMessage(event) {
+ log("Received " + event.data.length + " character utf-8 response from server.");
+ requestData();
+ }
+
+ function handleSocketClose() {
+ log("Socket closed.");
+ }
+
+ function handleSocketError() {
+ log("Socket error.")
+ }
+
+ function get_appropriate_ws_url()
+ {
+ var pcol;
+ var u = document.URL;
+
+ /*
+ * We open the websocket encrypted if this page came on an
+ * https:// url itself, otherwise unencrypted
+ */
+
+ if (u.substring(0, 5) == "https") {
+ pcol = "wss://";
+ u = u.substr(8);
+ } else {
+ pcol = "ws://";
+ if (u.substring(0, 4) == "http")
+ u = u.substr(7);
+ }
+
+ u = u.split('/');
+
+ return pcol + u[0];
+ }
+
+ </script>
+</head>
+<body>
+ <div>
+ <h1>Controls</h1>
+ <button onclick="clearLog()">Clear Log</button>
+ <button onclick="connect()">Connect</button>
+ <button onclick="disconnect()">Disconnect</button><br><br>
+ </div>
+ <div>
+ <h1>Output</h1>
+ <div id="output">Ready.</div>
+ </div>
+</body>
+</html>
diff --git a/test/scripts/fragmentation-test-server.js b/test/scripts/fragmentation-test-server.js
new file mode 100755
index 0000000..b1d71e5
--- /dev/null
+++ b/test/scripts/fragmentation-test-server.js
@@ -0,0 +1,151 @@
+#!/usr/bin/env node
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the 'License');
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an 'AS IS' BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+
+var WebSocketServer = require('../../lib/WebSocketServer');
+var WebSocketRouter = require('../../lib/WebSocketRouter');
+var http = require('http');
+var fs = require('fs');
+
+console.log('WebSocket-Node: Test server to spit out fragmented messages.');
+
+var args = {
+ 'no-fragmentation': false,
+ 'fragment': '16384',
+ 'port': '8080'
+};
+
+/* Parse command line options */
+var pattern = /^--(.*?)(?:=(.*))?$/;
+process.argv.forEach(function(value) {
+ var match = pattern.exec(value);
+ if (match) {
+ args[match[1]] = match[2] ? match[2] : true;
+ }
+});
+
+args.protocol = 'ws:';
+
+if (args.help) {
+ console.log('Usage: ./fragmentation-test-server.js [--port=8080] [--fragment=n] [--no-fragmentation]');
+ console.log('');
+ return;
+}
+else {
+ console.log('Use --help for usage information.');
+}
+
+var server = http.createServer(function(request, response) {
+ console.log((new Date()) + ' Received request for ' + request.url);
+ if (request.url === '/') {
+ fs.readFile('fragmentation-test-page.html', 'utf8', function(err, data) {
+ if (err) {
+ response.writeHead(404);
+ response.end();
+ }
+ else {
+ response.writeHead(200, {
+ 'Content-Type': 'text/html'
+ });
+ response.end(data);
+ }
+ });
+ }
+ else {
+ response.writeHead(404);
+ response.end();
+ }
+});
+server.listen(args.port, function() {
+ console.log((new Date()) + ' Server is listening on port ' + args.port);
+});
+
+var wsServer = new WebSocketServer({
+ httpServer: server,
+ fragmentOutgoingMessages: !args['no-fragmentation'],
+ fragmentationThreshold: parseInt(args['fragment'], 10)
+});
+
+var router = new WebSocketRouter();
+router.attachServer(wsServer);
+
+
+var lorem = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.';
+
+
+router.mount('*', 'fragmentation-test', function(request) {
+ var connection = request.accept(request.origin);
+ console.log((new Date()) + ' connection accepted from ' + connection.remoteAddress);
+
+
+ connection.on('message', function(message) {
+ function sendCallback(err) {
+ if (err) { console.error('send() error: ' + err); }
+ }
+ if (message.type === 'utf8') {
+ var length = 0;
+ var match = /sendMessage\|(\d+)/.exec(message.utf8Data);
+ var requestedLength;
+ if (match) {
+ requestedLength = parseInt(match[1], 10);
+ var longLorem = '';
+ while (length < requestedLength) {
+ longLorem += (' ' + lorem);
+ length = Buffer.byteLength(longLorem);
+ }
+ longLorem = longLorem.slice(0,requestedLength);
+ length = Buffer.byteLength(longLorem);
+ if (length > 0) {
+ connection.sendUTF(longLorem, sendCallback);
+ console.log((new Date()) + ' sent ' + length + ' byte utf-8 message to ' + connection.remoteAddress);
+ }
+ return;
+ }
+
+ match = /sendBinaryMessage\|(\d+)/.exec(message.utf8Data);
+ if (match) {
+ requestedLength = parseInt(match[1], 10);
+
+ // Generate random binary data.
+ var buffer = new Buffer(requestedLength);
+ for (var i=0; i < requestedLength; i++) {
+ buffer[i] = Math.ceil(Math.random()*255);
+ }
+
+ connection.sendBytes(buffer, sendCallback);
+ console.log((new Date()) + ' sent ' + buffer.length + ' byte binary message to ' + connection.remoteAddress);
+ return;
+ }
+ }
+ });
+
+ connection.on('close', function(reasonCode, description) {
+ console.log((new Date()) + ' peer ' + connection.remoteAddress + ' disconnected.');
+ });
+
+ connection.on('error', function(error) {
+ console.log('Connection error for peer ' + connection.remoteAddress + ': ' + error);
+ });
+});
+
+console.log('Point your WebSocket Protocol Version 8 compliant browser at http://localhost:' + args.port + '/');
+if (args['no-fragmentation']) {
+ console.log('Fragmentation disabled.');
+}
+else {
+ console.log('Fragmenting messages at ' + wsServer.config.fragmentationThreshold + ' bytes');
+}
diff --git a/test/scripts/libwebsockets-test-client.js b/test/scripts/libwebsockets-test-client.js
new file mode 100755
index 0000000..dcd9e2f
--- /dev/null
+++ b/test/scripts/libwebsockets-test-client.js
@@ -0,0 +1,101 @@
+#!/usr/bin/env node
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the 'License');
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an 'AS IS' BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+var WebSocketClient = require('../../lib/WebSocketClient');
+
+var args = { /* defaults */
+ secure: false,
+ version: 13
+};
+
+/* Parse command line options */
+var pattern = /^--(.*?)(?:=(.*))?$/;
+process.argv.forEach(function(value) {
+ var match = pattern.exec(value);
+ if (match) {
+ args[match[1]] = match[2] ? match[2] : true;
+ }
+});
+
+args.protocol = args.secure ? 'wss:' : 'ws:';
+args.version = parseInt(args.version, 10);
+
+if (!args.host || !args.port) {
+ console.log('WebSocket-Node: Test client for Andy Green\'s libwebsockets-test-server');
+ console.log('Usage: ./libwebsockets-test-client.js --host=127.0.0.1 --port=8080 [--version=8|13] [--secure]');
+ console.log('');
+ return;
+}
+
+var mirrorClient = new WebSocketClient({
+ webSocketVersion: args.version
+});
+
+mirrorClient.on('connectFailed', function(error) {
+ console.log('Connect Error: ' + error.toString());
+});
+
+mirrorClient.on('connect', function(connection) {
+ console.log('lws-mirror-protocol connected');
+ connection.on('error', function(error) {
+ console.log('Connection Error: ' + error.toString());
+ });
+ connection.on('close', function() {
+ console.log('lws-mirror-protocol Connection Closed');
+ });
+ function sendCallback(err) {
+ if (err) { console.error('send() error: ' + err); }
+ }
+ function spamCircles() {
+ if (connection.connected) {
+ // c #7A9237 487 181 14;
+ var color = 0x800000 + Math.round(Math.random() * 0x7FFFFF);
+ var x = Math.round(Math.random() * 502);
+ var y = Math.round(Math.random() * 306);
+ var radius = Math.round(Math.random() * 30);
+ connection.send('c #' + color.toString(16) + ' ' + x + ' ' + y + ' ' + radius + ';', sendCallback);
+ setTimeout(spamCircles, 10);
+ }
+ }
+ spamCircles();
+});
+
+mirrorClient.connect(args.protocol + '//' + args.host + ':' + args.port + '/', 'lws-mirror-protocol');
+
+
+var incrementClient = new WebSocketClient({
+ webSocketVersion: args.version
+});
+
+incrementClient.on('connectFailed', function(error) {
+ console.log('Connect Error: ' + error.toString());
+});
+
+incrementClient.on('connect', function(connection) {
+ console.log('dumb-increment-protocol connected');
+ connection.on('error', function(error) {
+ console.log('Connection Error: ' + error.toString());
+ });
+ connection.on('close', function() {
+ console.log('dumb-increment-protocol Connection Closed');
+ });
+ connection.on('message', function(message) {
+ console.log('Number: \'' + message.utf8Data + '\'');
+ });
+});
+
+incrementClient.connect(args.protocol + '//' + args.host + ':' + args.port + '/', 'dumb-increment-protocol');
diff --git a/test/scripts/libwebsockets-test-server.js b/test/scripts/libwebsockets-test-server.js
new file mode 100755
index 0000000..88a6fc1
--- /dev/null
+++ b/test/scripts/libwebsockets-test-server.js
@@ -0,0 +1,186 @@
+#!/usr/bin/env node
+/************************************************************************
+ * Copyright 2010-2015 Brian McKelvey.
+ *
+ * Licensed under the Apache License, Version 2.0 (the 'License');
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an 'AS IS' BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ***********************************************************************/
+
+
+var WebSocketServer = require('../../lib/WebSocketServer');
+var WebSocketRouter = require('../../lib/WebSocketRouter');
+var http = require('http');
+var fs = require('fs');
+
+var args = { /* defaults */
+ secure: false
+};
+
+/* Parse command line options */
+var pattern = /^--(.*?)(?:=(.*))?$/;
+process.argv.forEach(function(value) {
+ var match = pattern.exec(value);
+ if (match) {
+ args[match[1]] = match[2] ? match[2] : true;
+ }
+});
+
+args.protocol = args.secure ? 'wss:' : 'ws:';
+
+if (!args.port) {
+ console.log('WebSocket-Node: Test Server implementing Andy Green\'s');
+ console.log('libwebsockets-test-server protocols.');
+ console.log('Usage: ./libwebsockets-test-server.js --port=8080 [--secure]');
+ console.log('');
+ return;
+}
+
+if (args.secure) {
+ console.log('WebSocket-Node: Test Server implementing Andy Green\'s');
+ console.log('libwebsockets-test-server protocols.');
+ console.log('ERROR: TLS is not yet supported.');
+ console.log('');
+ return;
+}
+
+var server = http.createServer(function(request, response) {
+ console.log((new Date()) + ' Received request for ' + request.url);
+ if (request.url === '/') {
+ fs.readFile('libwebsockets-test.html', 'utf8', function(err, data) {
+ if (err) {
+ response.writeHead(404);
+ response.end();
+ }
+ else {
+ response.writeHead(200, {
+ 'Content-Type': 'text/html'
+ });
+ response.end(data);
+ }
+ });
+ }
+ else {
+ response.writeHead(404);
+ response.end();
+ }
+});
+server.listen(args.port, function() {
+ console.log((new Date()) + ' Server is listening on port ' + args.port);
+});
+
+var wsServer = new WebSocketServer({
+ httpServer: server
+});
+
+var router = new WebSocketRouter();
+router.attachServer(wsServer);
+
+
+var mirrorConnections = [];
+
+var mirrorHistory = [];
+
+function sendCallback(err) {
+ if (err) { console.error('send() error: ' + err); }
+}
+
+router.mount('*', 'lws-mirror-protocol', function(request) {
+ var cookies = [
+ {
+ name: 'TestCookie',
+ value: 'CookieValue' + Math.floor(Math.random()*1000),
+ path: '/',
+ secure: false,
+ maxage: 5000,
+ httponly: true
+ }
+ ];
+
+ // Should do origin verification here. You have to pass the accepted
+ // origin into the accept method of the request.
+ var connection = request.accept(request.origin, cookies);
+ console.log((new Date()) + ' lws-mirror-protocol connection accepted from ' + connection.remoteAddress +
+ ' - Protocol Version ' + connection.webSocketVersion);
+
+
+
+ if (mirrorHistory.length > 0) {
+ var historyString = mirrorHistory.join('');
+ console.log((new Date()) + ' sending mirror protocol history to client; ' + connection.remoteAddress + ' : ' + Buffer.byteLength(historyString) + ' bytes');
+
+ connection.send(historyString, sendCallback);
+ }
+
+ mirrorConnections.push(connection);
+
+ connection.on('message', function(message) {
+ // We only care about text messages
+ if (message.type === 'utf8') {
+ // Clear canvas command received
+ if (message.utf8Data === 'clear;') {
+ mirrorHistory = [];
+ }
+ else {
+ // Record all other commands in the history
+ mirrorHistory.push(message.utf8Data);
+ }
+
+ // Re-broadcast the command to all connected clients
+ mirrorConnections.forEach(function (outputConnection) {
+ outputConnection.send(message.utf8Data, sendCallback);
+ });
+ }
+ });
+
+ connection.on('close', function(closeReason, description) {
+ var index = mirrorConnections.indexOf(connection);
+ if (index !== -1) {
+ console.log((new Date()) + ' lws-mirror-protocol peer ' + connection.remoteAddress + ' disconnected, code: ' + closeReason + '.');
+ mirrorConnections.splice(index, 1);
+ }
+ });
+
+ connection.on('error', function(error) {
+ console.log('Connection error for peer ' + connection.remoteAddress + ': ' + error);
+ });
+});
+
+router.mount('*', 'dumb-increment-protocol', function(request) {
+ // Should do origin verification here. You have to pass the accepted
+ // origin into the accept method of the request.
+ var connection = request.accept(request.origin);
+ console.log((new Date()) + ' dumb-increment-protocol connection accepted from ' + connection.remoteAddress +
+ ' - Protocol Version ' + connection.webSocketVersion);
+
+ var number = 0;
+ connection.timerInterval = setInterval(function() {
+ connection.send((number++).toString(10), sendCallback);
+ }, 50);
+ connection.on('close', function() {
+ clearInterval(connection.timerInterval);
+ });
+ connection.on('message', function(message) {
+ if (message.type === 'utf8') {
+ if (message.utf8Data === 'reset\n') {
+ console.log((new Date()) + ' increment reset received');
+ number = 0;
+ }
+ }
+ });
+ connection.on('close', function(closeReason, description) {
+ console.log((new Date()) + ' dumb-increment-protocol peer ' + connection.remoteAddress + ' disconnected, code: ' + closeReason + '.');
+ });
+});
+
+console.log('WebSocket-Node: Test Server implementing Andy Green\'s');
+console.log('libwebsockets-test-server protocols.');
+console.log('Point your WebSocket Protocol Version 8 complant browser to http://localhost:' + args.port + '/');
diff --git a/test/scripts/libwebsockets-test.html b/test/scripts/libwebsockets-test.html
new file mode 100644
index 0000000..74437aa
--- /dev/null
+++ b/test/scripts/libwebsockets-test.html
@@ -0,0 +1,253 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset=utf-8 />
+ <title>Minimal Websocket test app</title>
+</head>
+
+<body>
+<h2>libwebsockets "dumb-increment-protocol" test applet</h2>
+The incrementing number is coming from the server and is individual for
+each connection to the server... try opening a second browser window.
+Click the button to send the server a websocket message to
+reset the number.<br><br>
+
+<table>
+ <tr>
+ <td align=center>
+ <input type=button id=offset value="Reset counter" onclick="reset();">
+ <input type=button id=offset value="Disconnect" onclick="closeIncrementConnection();">
+ </td>
+ <td width=100 align=center><div id=number> </div></td>
+ <td id=wsdi_statustd align=center><div id=wsdi_status>Not initialized</div></td>
+ </tr>
+</table>
+
+<h2>libwebsockets "lws-mirror-protocol" test applet</h2>
+Use the mouse to draw on the canvas below -- all other browser windows open
+on this page see your drawing in realtime and you can see any of theirs as
+well.
+<p>
+The lws-mirror protocol doesn't interpret what is being sent to it, it just
+re-sends it to every other websocket it has a connection with using that
+protocol, including the guy who sent the packet.
+<p>libwebsockets-test-client spams circles on to this shared canvas when
+run.</p>
+<br><br>
+
+<table>
+ <tr>
+ <td>Drawing color:
+ <select id="color" onchange="update_color();">
+ <option value=#000000>Black</option>
+ <option value=#0000ff>Blue</option>
+ <option value=#20ff20>Green</option>
+ <option value=#802020>Dark Red</option>
+ </select>
+ </td>
+ <td id=wslm_statustd align=center><div id=wslm_status>Not initialized</div></td>
+ </tr>
+ <tr>
+ <button id="clearCanvasButton" onclick="clearCanvas()">Clear Canvas</button>
+ </tr>
+ <tr>
+ <td colspan=2 width=500 align=center style="background-color: #e0e0e0;"><div id="wslm_drawing"> </div></td>
+ </tr>
+</table>
+
+<script>
+ var pos = 0;
+
+function get_appropriate_ws_url()
+{
+ var pcol;
+ var u = document.URL;
+
+ /*
+ * We open the websocket encrypted if this page came on an
+ * https:// url itself, otherwise unencrypted
+ */
+
+ if (u.substring(0, 5) == "https") {
+ pcol = "wss://";
+ u = u.substr(8);
+ } else {
+ pcol = "ws://";
+ if (u.substring(0, 4) == "http")
+ u = u.substr(7);
+ }
+
+ u = u.split('/');
+
+ return pcol + u[0];
+}
+
+
+document.getElementById("number").textContent = get_appropriate_ws_url();
+
+/* dumb increment protocol */
+
+ var ws_ctor = window['MozWebSocket'] ? window['MozWebSocket'] : window['WebSocket'];
+
+ var socket_di = new ws_ctor(get_appropriate_ws_url(),
+ "dumb-increment-protocol");
+
+ try {
+ socket_di.onopen = function() {
+ document.getElementById("wsdi_statustd").style.backgroundColor = "#40ff40";
+ document.getElementById("wsdi_status").textContent = " websocket connection opened ";
+ }
+
+ socket_di.onmessage =function got_packet(msg) {
+ document.getElementById("number").textContent = msg.data + "\n";
+ }
+
+ socket_di.onclose = function(){
+ document.getElementById("wsdi_statustd").style.backgroundColor = "#ff4040";
+ document.getElementById("wsdi_status").textContent = " websocket connection CLOSED ";
+ }
+ } catch(exception) {
+ alert('<p>Error' + exception);
+ }
+
+function reset() {
+ socket_di.send("reset\n");
+}
+
+function closeIncrementConnection() {
+ socket_di.close();
+}
+
+/* lws-mirror protocol */
+
+ var down = 0;
+ var no_last = 1;
+ var last_x = 0, last_y = 0;
+ var ctx;
+
+ var ws_ctor = window['MozWebSocket'] ? window['MozWebSocket'] : window['WebSocket'];
+
+ var socket_lm = new ws_ctor(get_appropriate_ws_url(),
+ "lws-mirror-protocol");
+ var color = "#000000";
+
+ var lws_error = false;
+
+ try {
+ socket_lm.onopen = function() {
+ document.getElementById("wslm_statustd").style.backgroundColor = "#40ff40";
+ document.getElementById("wslm_status").textContent = " websocket connection opened ";
+ }
+
+ socket_lm.onerror = function(error) {
+ lws_error = true;
+ document.getElementById("wslm_statustd").style.backgroundColor = "#ff4040";
+ document.getElementById("wslm_status").textContent = " websocket connection ERROR ";
+ };
+
+ socket_lm.onmessage =function got_packet(msg) {
+ j = msg.data.split(';');
+ f = 0;
+ while (f < j.length - 1) {
+ i = j[f].split(' ');
+ if (i[0] == 'd') {
+ ctx.strokeStyle = i[1];
+ ctx.beginPath();
+ ctx.moveTo(+(i[2]), +(i[3]));
+ ctx.lineTo(+(i[4]), +(i[5]));
+ ctx.stroke();
+ }
+ if (i[0] == 'clear') {
+ ctx.clearRect(0,0,480,300);
+ }
+ if (i[0] == 'c') {
+ ctx.strokeStyle = i[1];
+ ctx.beginPath();
+ ctx.arc(+(i[2]), +(i[3]), +(i[4]), 0, Math.PI*2, true);
+ ctx.stroke();
+ }
+
+ f++;
+ }
+ }
+
+ socket_lm.onclose = function(){
+ if (!lws_error) {
+ document.getElementById("wslm_statustd").style.backgroundColor = "#ff4040";
+ document.getElementById("wslm_status").textContent = " websocket connection CLOSED ";
+ }
+ }
+ } catch(exception) {
+ alert('<p>Error' + exception);
+ }
+
+ var canvas = document.createElement('canvas');
+ canvas.height = 300;
+ canvas.width = 480;
+ ctx = canvas.getContext("2d");
+
+ document.getElementById('wslm_drawing').appendChild(canvas);
+
+ canvas.addEventListener('mousemove', ev_mousemove, false);
+ canvas.addEventListener('mousedown', ev_mousedown, false);
+ canvas.addEventListener('mouseup', ev_mouseup, false);
+
+ offsetX = offsetY = 0;
+ element = canvas;
+ if (element.offsetParent) {
+ do {
+ offsetX += element.offsetLeft;
+ offsetY += element.offsetTop;
+ } while ((element = element.offsetParent));
+ }
+
+function update_color() {
+ color = document.getElementById("color").value;
+}
+
+function ev_mousedown (ev) {
+ down = 1;
+}
+
+function ev_mouseup(ev) {
+ down = 0;
+ no_last = 1;
+}
+
+function ev_mousemove (ev) {
+ var x, y;
+
+ if (ev.offsetX) {
+ x = ev.offsetX;
+ y = ev.offsetY;
+ } else {
+ x = ev.layerX - offsetX;
+ y = ev.layerY - offsetY;
+
+ }
+
+ if (!down)
+ return;
+ if (no_last) {
+ no_last = 0;
+ last_x = x;
+ last_y = y;
+ return;
+ }
+ if (socket_lm.readyState === ws_ctor.OPEN)
+ socket_lm.send("d " + color + " " + last_x + " " + last_y + " " + x + ' ' + y + ';');
+
+ last_x = x;
+ last_y = y;
+}
+
+function clearCanvas() {
+ if (socket_lm.readyState === ws_ctor.OPEN)
+ socket_lm.send("clear;");
+}
+
+
+</script>
+
+</body>
+</html>
diff --git a/test/scripts/memoryleak-client.js b/test/scripts/memoryleak-client.js
new file mode 100644
index 0000000..04bc37a
--- /dev/null
+++ b/test/scripts/memoryleak-client.js
@@ -0,0 +1,96 @@
+var WebSocketClient = require('../../lib/websocket').client;
+
+var connectionAmount = process.argv[2];
+var activeCount = 0;
+var deviceList = [];
+
+connectDevices();
+
+function logActiveCount() {
+ console.log('---activecount---: ' + activeCount);
+}
+
+setInterval(logActiveCount, 500);
+
+function connectDevices() {
+ for( var i=0; i < connectionAmount; i++ ){
+ connect( i );
+ }
+}
+
+function connect( i ){
+ // console.log( '--- Connecting: ' + i );
+ var client = new WebSocketClient({
+ tlsOptions: {
+ rejectUnauthorized: false
+ }
+ });
+ client._clientID = i;
+ deviceList[i] = client;
+
+ client.on('connectFailed', function(error) {
+ console.log(i + ' - connect Error: ' + error.toString());
+ });
+
+ client.on('connect', function(connection) {
+ console.log(i + ' - connect');
+ activeCount ++;
+ client.connection = connection;
+ flake( i );
+
+ maybeScheduleSend(i);
+
+ connection.on('error', function(error) {
+ console.log(i + ' - ' + error.toString());
+ });
+
+ connection.on('close', function(reasonCode, closeDescription) {
+ console.log(i + ' - close (%d) %s', reasonCode, closeDescription);
+ activeCount --;
+ if (client._flakeTimeout) {
+ clearTimeout(client._flakeTimeout);
+ client._flakeTimeout = null;
+ }
+ connect(i);
+ });
+
+ connection.on('message', function(message) {
+ if ( message.type === 'utf8' ) {
+ console.log(i + ' received: \'' + message.utf8Data + '\'');
+ }
+ });
+
+ });
+ client.connect('wss://localhost:8080');
+}
+
+function disconnect( i ){
+ var client = deviceList[i];
+ if (client._flakeTimeout) {
+ client._flakeTimeout = null;
+ }
+ client.connection.close();
+}
+
+function maybeScheduleSend(i) {
+ var client = deviceList[i];
+ var random = Math.round(Math.random() * 100);
+ console.log(i + ' - scheduling send. Random: ' + random);
+ if (random < 50) {
+ setTimeout(function() {
+ console.log(i + ' - send timeout. Connected? ' + client.connection.connected);
+ if (client && client.connection.connected) {
+ console.log(i + ' - Sending test data! random: ' + random);
+ client.connection.send( (new Array(random)).join('TestData') );
+ }
+ }, random);
+ }
+}
+
+function flake(i) {
+ var client = deviceList[i];
+ var timeBeforeDisconnect = Math.round(Math.random() * 2000);
+ client._flakeTimeout = setTimeout( function() {
+ disconnect(i);
+ }, timeBeforeDisconnect);
+}
diff --git a/test/scripts/memoryleak-server.js b/test/scripts/memoryleak-server.js
new file mode 100644
index 0000000..2b07841
--- /dev/null
+++ b/test/scripts/memoryleak-server.js
@@ -0,0 +1,59 @@
+process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
+
+// var heapdump = require('heapdump');
+// var memwatch = require('memwatch');
+var fs = require('fs');
+var WebSocketServer = require('../../lib/websocket').server;
+var https = require('https');
+
+var activeCount = 0;
+
+var config = {
+ key: fs.readFileSync( 'privatekey.pem' ),
+ cert: fs.readFileSync( 'certificate.pem' )
+};
+
+var server = https.createServer( config );
+
+server.listen(8080, function() {
+ console.log((new Date()) + ' Server is listening on port 8080 (wss)');
+});
+
+var wsServer = new WebSocketServer({
+ httpServer: server,
+ autoAcceptConnections: false
+});
+
+wsServer.on('request', function(request) {
+ activeCount++;
+ console.log('Opened from: %j\n---activeCount---: %d', request.remoteAddresses, activeCount);
+ var connection = request.accept(null, request.origin);
+ console.log((new Date()) + ' Connection accepted.');
+ connection.on('message', function(message) {
+ if (message.type === 'utf8') {
+ console.log('Received Message: ' + message.utf8Data);
+ setTimeout(function() {
+ if (connection.connected) {
+ connection.sendUTF(message.utf8Data);
+ }
+ }, 1000);
+ }
+ });
+ connection.on('close', function(reasonCode, description) {
+ activeCount--;
+ console.log('Closed. (' + reasonCode + ') ' + description +
+ '\n---activeCount---: ' + activeCount);
+ // connection._debug.printOutput();
+ });
+ connection.on('error', function(error) {
+ console.log('Connection error: ' + error);
+ });
+});
+
+// setInterval( function(){
+// // global.gc();
+// var filename = './heapdump/'+ new Date().getTime() + '_' + activeCount + '.heapsnapshot';
+// console.log('Triggering heapdump to write to %s', filename);
+// heapdump.writeSnapshot( filename );
+// }, 10000 );
+// memwatch.on('leak', function(info) { console.log(info); });
diff --git a/test/scripts/privatekey.pem b/test/scripts/privatekey.pem
new file mode 100644
index 0000000..ac2cb9e
--- /dev/null
+++ b/test/scripts/privatekey.pem
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXQIBAAKBgQCpX8/M7iA86+s0N91CRj1e83LEuJ48M6MrCJBosYYWKz983sw0
+Kf1QviW5dhAzT5R1AdGyvddVd80z5J9tNZqje2vyrXssClq+iETxW8U71wfUZ/Vm
+GhWcXwU7XD4JP33WbTIEHS2xgpMQNXQnQFM40+NjQBViK0b9mQtclOliqwIDAQAB
+AoGAS5yrPtg7ahcD7E7YJsMGmMHjxXCJq2R9/jMXjLVbn7/02sD3tn3cSVRpsO7E
+8rMfGlESlVHstIoEAJualH1up7y2fLd2KFoHJ+7tCH0VHXsNp07XVDCnjrTH3z7J
+DRt6RjoKDqra1os+CzV+C+NnNvIt74+KSo06JjQVb5ZRmXECQQDcPIFKFK8LZVlX
+9cZrhRLW7K3g8K2BE3tmaocTk3T+0+u0cK9OaNIuEcj3cM3H35DtA4kXtNCRmjA+
+ytDmzLH5AkEAxODoU/ve4YuU0r7OTzxd0G9FLuif2ktqfqid185BBH6/K4SttXob
+yI93h261jVHZ9RgifXs/MBdCmeB5GODiwwJBAINeQ/CgbdlqVuS04ep4skgpXX5z
+kcsQh+cLXA89QehPGKXFIYyv0c9RJIMUcmrq3FPEbB4L6O0w/940tG83YmECQQCv
+BhrEfse3zzTw3bvfaRUltaXVe+yQTjdQfmpEbhITAvLEp2EeUn3coN5sQhmYlsmj
+QF95GlYkVKlaztoZKeOtAkB0uNhifHAfCi4mUVzRb+oWrju1pRgHoTXQUh98XWpL
+Am8gTOfkcszD+Kg+weCH1V0LJelptTJ/5dSpDRfI+I2S
+-----END RSA PRIVATE KEY-----
diff --git a/test/shared/start-echo-server.js b/test/shared/start-echo-server.js
new file mode 100644
index 0000000..9dbd980
--- /dev/null
+++ b/test/shared/start-echo-server.js
@@ -0,0 +1,56 @@
+module.exports = startEchoServer;
+
+function startEchoServer(outputStream, callback) {
+ if ('function' === typeof outputStream) {
+ callback = outputStream;
+ outputStream = null;
+ }
+ if ('function' !== typeof callback) {
+ callback = function(){};
+ }
+
+ var path = require('path').join(__dirname + '/../scripts/echo-server.js');
+
+ console.log(path);
+
+ var echoServer = require('child_process').spawn('node', [ path ]);
+
+ var state = 'starting';
+
+ var processProxy = {
+ kill: function(signal) {
+ state = 'exiting';
+ echoServer.kill(signal);
+ }
+ };
+
+ if (outputStream) {
+ echoServer.stdout.pipe(outputStream);
+ echoServer.stderr.pipe(outputStream);
+ }
+
+ echoServer.stdout.on('data', function(chunk) {
+ chunk = chunk.toString();
+ if (/Server is listening/.test(chunk)) {
+ if (state === 'starting') {
+ state = 'ready';
+ callback(null, processProxy);
+ }
+ }
+ });
+
+ echoServer.on('exit', function(code, signal) {
+ echoServer = null;
+ if (state !== 'exiting') {
+ state = 'exited';
+ callback(new Error('Echo Server exited unexpectedly with code ' + code));
+ process.exit(1);
+ }
+ });
+
+ process.on('exit', function() {
+ if (echoServer && state === 'ready') {
+ echoServer.kill();
+ }
+ });
+}
diff --git a/test/shared/test-server.js b/test/shared/test-server.js
new file mode 100644
index 0000000..78a9cae
--- /dev/null
+++ b/test/shared/test-server.js
@@ -0,0 +1,45 @@
+var http = require('http');
+var WebSocketServer = require('../../lib/WebSocketServer');
+
+var server;
+var wsServer;
+
+function prepare(callback) {
+ if (typeof(callback) !== 'function') { callback = function(){}; }
+ server = http.createServer(function(request, response) {
+ response.writeHead(404);
+ response.end();
+ });
+
+ wsServer = new WebSocketServer({
+ httpServer: server,
+ autoAcceptConnections: false,
+ maxReceivedFrameSize: 64*1024*1024, // 64MiB
+ maxReceivedMessageSize: 64*1024*1024, // 64MiB
+ fragmentOutgoingMessages: false,
+ keepalive: false,
+ disableNagleAlgorithm: false
+ });
+
+ server.listen(64321, function(err) {
+ if (err) {
+ return callback(err);
+ }
+ callback(null, wsServer);
+ });
+}
+
+function stopServer() {
+ try {
+ wsServer.shutDown();
+ server.close();
+ }
+ catch(e) {
+ console.warn('stopServer threw', e);
+ }
+}
+
+module.exports = {
+ prepare: prepare,
+ stopServer: stopServer
+};
diff --git a/test/unit/dropBeforeAccept.js b/test/unit/dropBeforeAccept.js
new file mode 100644
index 0000000..c13a7e6
--- /dev/null
+++ b/test/unit/dropBeforeAccept.js
@@ -0,0 +1,63 @@
+#!/usr/bin/env node
+
+var test = require('tape');
+
+var WebSocketClient = require('../../lib/WebSocketClient');
+var server = require('../shared/test-server');
+var stopServer = server.stopServer;
+
+test('Drop TCP Connection Before server accepts the request', function(t) {
+ t.plan(5);
+
+ server.prepare(function(err, wsServer) {
+ if (err) {
+ t.fail('Unable to start test server');
+ return t.end();
+ }
+
+ wsServer.on('connect', function(connection) {
+ t.pass('Server should emit connect event');
+ });
+
+ wsServer.on('request', function(request) {
+ t.pass('Request received');
+
+ // Wait 500 ms before accepting connection
+ setTimeout(function() {
+ var connection = request.accept(request.requestedProtocols[0], request.origin);
+
+ connection.on('close', function(reasonCode, description) {
+ t.pass('Connection should emit close event');
+ t.equal(reasonCode, 1006, 'Close reason code should be 1006');
+ t.equal(description,
+ 'TCP connection lost before handshake completed.',
+ 'Description should be correct');
+ t.end();
+ stopServer();
+ });
+
+ connection.on('error', function(error) {
+ t.fail('No error events should be received on the connection');
+ stopServer();
+ });
+
+ }, 500);
+ });
+
+ var client = new WebSocketClient();
+ client.on('connect', function(connection) {
+ t.fail('Client should never connect.');
+ connection.drop();
+ stopServer();
+ t.end();
+ });
+
+ client.connect('ws://localhost:64321/', ['test']);
+
+ setTimeout(function() {
+ // Bail on the connection before we hear back from the server.
+ client.abort();
+ }, 250);
+
+ });
+});
diff --git a/test/unit/regressions.js b/test/unit/regressions.js
new file mode 100644
index 0000000..9a46a9e
--- /dev/null
+++ b/test/unit/regressions.js
@@ -0,0 +1,31 @@
+var test = require('tape');
+
+var WebSocketClient = require('../../lib/WebSocketClient');
+var startEchoServer = require('../shared/start-echo-server');
+
+test('Issue 195 - passing number to connection.send() shouldn\'t throw', function(t) {
+ startEchoServer(function(err, echoServer) {
+ if (err) { return t.fail('Unable to start echo server: ' + err); }
+
+ var client = new WebSocketClient();
+ client.on('connect', function(connection) {
+ t.pass('connected');
+
+ t.doesNotThrow(function() {
+ connection.send(12345);
+ });
+
+ connection.close();
+ echoServer.kill();
+ t.end();
+ });
+
+ client.on('connectFailed', function(errorDescription) {
+ echoServer.kill();
+ t.fail(errorDescription);
+ t.end();
+ });
+
+ client.connect('ws://localhost:8080', null);
+ });
+});
diff --git a/test/unit/request.js b/test/unit/request.js
new file mode 100644
index 0000000..f5cc69a
--- /dev/null
+++ b/test/unit/request.js
@@ -0,0 +1,105 @@
+var test = require('tape');
+
+var WebSocketClient = require('../../lib/WebSocketClient');
+var server = require('../shared/test-server');
+var stopServer = server.stopServer;
+
+test('Request can only be rejected or accepted once.', function(t) {
+ t.plan(6);
+
+ t.on('end', function() {
+ stopServer();
+ });
+
+ server.prepare(function(err, wsServer) {
+ if (err) {
+ t.fail('Unable to start test server');
+ return t.end();
+ }
+
+ wsServer.once('request', firstReq);
+ connect(2);
+
+ function firstReq(request) {
+ var accept = request.accept.bind(request, request.requestedProtocols[0], request.origin);
+ var reject = request.reject.bind(request);
+
+ t.doesNotThrow(accept, 'First call to accept() should succeed.');
+ t.throws(accept, 'Second call to accept() should throw.');
+ t.throws(reject, 'Call to reject() after accept() should throw.');
+
+ wsServer.once('request', secondReq);
+ }
+
+ function secondReq(request) {
+ var accept = request.accept.bind(request, request.requestedProtocols[0], request.origin);
+ var reject = request.reject.bind(request);
+
+ t.doesNotThrow(reject, 'First call to reject() should succeed.');
+ t.throws(reject, 'Second call to reject() should throw.');
+ t.throws(accept, 'Call to accept() after reject() should throw.');
+
+ t.end();
+ }
+
+ function connect(numTimes) {
+ var client;
+ for (var i=0; i < numTimes; i++) {
+ client = new WebSocketClient();
+ client.connect('ws://localhost:64321/', 'foo');
+ client.on('connect', function(connection) { connection.close(); });
+ }
+ }
+ });
+});
+
+
+test('Protocol mismatch should be handled gracefully', function(t) {
+ var wsServer;
+
+ t.test('setup', function(t) {
+ server.prepare(function(err, result) {
+ if (err) {
+ t.fail('Unable to start test server');
+ return t.end();
+ }
+
+ wsServer = result;
+ t.end();
+ });
+ });
+
+ t.test('mismatched protocol connection', function(t) {
+ t.plan(2);
+ wsServer.on('request', handleRequest);
+
+ var client = new WebSocketClient();
+
+ var timer = setTimeout(function() {
+ t.fail('Timeout waiting for client event');
+ }, 2000);
+
+ client.connect('ws://localhost:64321/', 'some_protocol_here');
+ client.on('connect', function(connection) {
+ clearTimeout(timer);
+ connection.close();
+ t.fail('connect event should not be emitted on client');
+ });
+ client.on('connectFailed', function() {
+ clearTimeout(timer);
+ t.pass('connectFailed event should be emitted on client');
+ });
+
+
+
+ function handleRequest(request) {
+ var accept = request.accept.bind(request, 'this_is_the_wrong_protocol', request.origin);
+ t.throws(accept, 'request.accept() should throw');
+ }
+ });
+
+ t.test('teardown', function(t) {
+ stopServer();
+ t.end();
+ });
+});
diff --git a/test/unit/w3cwebsocket.js b/test/unit/w3cwebsocket.js
new file mode 100755
index 0000000..e4ad230
--- /dev/null
+++ b/test/unit/w3cwebsocket.js
@@ -0,0 +1,76 @@
+#!/usr/bin/env node
+
+var test = require('tape');
+var WebSocket = require('../../lib/W3CWebSocket');
+var startEchoServer = require('../shared/start-echo-server');
+
+test('W3CWebSockets adding event listeners with ws.onxxxxx', function(t) {
+ var counter = 0;
+ var message = 'This is a test message.';
+
+ startEchoServer(function(err, echoServer) {
+ if (err) { return t.fail('Unable to start echo server: ' + err); }
+
+ var ws = new WebSocket('ws://localhost:8080/');
+
+ ws.onopen = function() {
+ t.equal(++counter, 1, 'onopen should be called first');
+
+ ws.send(message);
+ };
+ ws.onerror = function(event) {
+ t.fail('No errors are expected: ' + event);
+ };
+ ws.onmessage = function(event) {
+ t.equal(++counter, 2, 'onmessage should be called second');
+
+ t.equal(event.data, message, 'Received message data should match sent message data.');
+
+ ws.close();
+ };
+ ws.onclose = function(event) {
+ t.equal(++counter, 3, 'onclose should be called last');
+
+ echoServer.kill();
+
+ t.end();
+ };
+ });
+});
+
+test('W3CWebSockets adding event listeners with ws.addEventListener', function(t) {
+ var counter = 0;
+ var message = 'This is a test message.';
+
+ startEchoServer(function(err, echoServer) {
+ if (err) { return t.fail('Unable to start echo server: ' + err); }
+
+ var ws = new WebSocket('ws://localhost:8080/');
+
+ ws.addEventListener('open', function() {
+ t.equal(++counter, 1, '"open" should be fired first');
+
+ ws.send(message);
+ });
+ ws.addEventListener('error', function(event) {
+ t.fail('No errors are expected: ' + event);
+ });
+ ws.addEventListener('message', function(event) {
+ t.equal(++counter, 2, '"message" should be fired second');
+
+ t.equal(event.data, message, 'Received message data should match sent message data.');
+
+ ws.close();
+ });
+ ws.addEventListener('close', function(event) {
+ t.equal(++counter, 3, '"close" should be fired');
+ });
+ ws.addEventListener('close', function(event) {
+ t.equal(++counter, 4, '"close" should be fired one more time');
+
+ echoServer.kill();
+
+ t.end();
+ });
+ });
+});
diff --git a/test/unit/websocketFrame.js b/test/unit/websocketFrame.js
new file mode 100644
index 0000000..034612e
--- /dev/null
+++ b/test/unit/websocketFrame.js
@@ -0,0 +1,32 @@
+#!/usr/bin/env node
+
+var test = require('tape');
+var bufferEqual = require('buffer-equal');
+var WebSocketFrame = require('../../lib/WebSocketFrame');
+
+test('Serializing a WebSocket Frame with no data', function(t) {
+ t.plan(2);
+
+ // WebSocketFrame uses a per-connection buffer for the mask bytes
+ // and the frame header to avoid allocating tons of small chunks of RAM.
+ var maskBytesBuffer = new Buffer(4);
+ var frameHeaderBuffer = new Buffer(10);
+
+ var frameBytes;
+ var frame = new WebSocketFrame(maskBytesBuffer, frameHeaderBuffer, {});
+ frame.fin = true;
+ frame.mask = true;
+ frame.opcode = 0x09; // WebSocketFrame.PING
+ t.doesNotThrow(
+ function() { frameBytes = frame.toBuffer(true); },
+ 'should not throw an error'
+ );
+
+ t.assert(
+ bufferEqual
+ (frameBytes, new Buffer('898000000000', 'hex')),
+ 'Generated bytes should be correct'
+ );
+
+ t.end();
+}); \ No newline at end of file
diff --git a/vendor/FastBufferList.js b/vendor/FastBufferList.js
new file mode 100644
index 0000000..aabf096
--- /dev/null
+++ b/vendor/FastBufferList.js
@@ -0,0 +1,193 @@
+// This file was copied from https://github.com/substack/node-bufferlist
+// and modified to be able to copy bytes from the bufferlist directly into
+// a pre-existing fixed-size buffer without an additional memory allocation.
+
+// bufferlist.js
+// Treat a linked list of buffers as a single variable-size buffer.
+var Buffer = require('buffer').Buffer;
+var EventEmitter = require('events').EventEmitter;
+
+module.exports = BufferList;
+module.exports.BufferList = BufferList; // backwards compatibility
+
+function BufferList(opts) {
+ if (!(this instanceof BufferList)) return new BufferList(opts);
+ EventEmitter.call(this);
+ var self = this;
+
+ if (typeof(opts) == 'undefined') opts = {};
+
+ // default encoding to use for take(). Leaving as 'undefined'
+ // makes take() return a Buffer instead.
+ self.encoding = opts.encoding;
+
+ // constructor to use for Buffer-esque operations
+ self.construct = opts.construct || Buffer;
+
+ var head = { next : null, buffer : null };
+ var last = { next : null, buffer : null };
+
+ // length can get negative when advanced past the end
+ // and this is the desired behavior
+ var length = 0;
+ self.__defineGetter__('length', function () {
+ return length;
+ });
+
+ // keep an offset of the head to decide when to head = head.next
+ var offset = 0;
+
+ // Write to the bufferlist. Emits 'write'. Always returns true.
+ self.write = function (buf) {
+ if (!head.buffer) {
+ head.buffer = buf;
+ last = head;
+ }
+ else {
+ last.next = { next : null, buffer : buf };
+ last = last.next;
+ }
+ length += buf.length;
+ self.emit('write', buf);
+ return true;
+ };
+
+ self.end = function (buf) {
+ if (Buffer.isBuffer(buf)) self.write(buf);
+ };
+
+ // Push buffers to the end of the linked list. (deprecated)
+ // Return this (self).
+ self.push = function () {
+ var args = [].concat.apply([], arguments);
+ args.forEach(self.write);
+ return self;
+ };
+
+ // For each buffer, perform some action.
+ // If fn's result is a true value, cut out early.
+ // Returns this (self).
+ self.forEach = function (fn) {
+ if (!head.buffer) return new self.construct(0);
+
+ if (head.buffer.length - offset <= 0) return self;
+ var firstBuf = head.buffer.slice(offset);
+
+ var b = { buffer : firstBuf, next : head.next };
+
+ while (b && b.buffer) {
+ var r = fn(b.buffer);
+ if (r) break;
+ b = b.next;
+ }
+
+ return self;
+ };
+
+ // Create a single Buffer out of all the chunks or some subset specified by
+ // start and one-past the end (like slice) in bytes.
+ self.join = function (start, end) {
+ if (!head.buffer) return new self.construct(0);
+ if (start == undefined) start = 0;
+ if (end == undefined) end = self.length;
+
+ var big = new self.construct(end - start);
+ var ix = 0;
+ self.forEach(function (buffer) {
+ if (start < (ix + buffer.length) && ix < end) {
+ // at least partially contained in the range
+ buffer.copy(
+ big,
+ Math.max(0, ix - start),
+ Math.max(0, start - ix),
+ Math.min(buffer.length, end - ix)
+ );
+ }
+ ix += buffer.length;
+ if (ix > end) return true; // stop processing past end
+ });
+
+ return big;
+ };
+
+ self.joinInto = function (targetBuffer, targetStart, sourceStart, sourceEnd) {
+ if (!head.buffer) return new self.construct(0);
+ if (sourceStart == undefined) sourceStart = 0;
+ if (sourceEnd == undefined) sourceEnd = self.length;
+
+ var big = targetBuffer;
+ if (big.length - targetStart < sourceEnd - sourceStart) {
+ throw new Error("Insufficient space available in target Buffer.");
+ }
+ var ix = 0;
+ self.forEach(function (buffer) {
+ if (sourceStart < (ix + buffer.length) && ix < sourceEnd) {
+ // at least partially contained in the range
+ buffer.copy(
+ big,
+ Math.max(targetStart, targetStart + ix - sourceStart),
+ Math.max(0, sourceStart - ix),
+ Math.min(buffer.length, sourceEnd - ix)
+ );
+ }
+ ix += buffer.length;
+ if (ix > sourceEnd) return true; // stop processing past end
+ });
+
+ return big;
+ };
+
+ // Advance the buffer stream by n bytes.
+ // If n the aggregate advance offset passes the end of the buffer list,
+ // operations such as .take() will return empty strings until enough data is
+ // pushed.
+ // Returns this (self).
+ self.advance = function (n) {
+ offset += n;
+ length -= n;
+ while (head.buffer && offset >= head.buffer.length) {
+ offset -= head.buffer.length;
+ head = head.next
+ ? head.next
+ : { buffer : null, next : null }
+ ;
+ }
+ if (head.buffer === null) last = { next : null, buffer : null };
+ self.emit('advance', n);
+ return self;
+ };
+
+ // Take n bytes from the start of the buffers.
+ // Returns a string.
+ // If there are less than n bytes in all the buffers or n is undefined,
+ // returns the entire concatenated buffer string.
+ self.take = function (n, encoding) {
+ if (n == undefined) n = self.length;
+ else if (typeof n !== 'number') {
+ encoding = n;
+ n = self.length;
+ }
+ var b = head;
+ if (!encoding) encoding = self.encoding;
+ if (encoding) {
+ var acc = '';
+ self.forEach(function (buffer) {
+ if (n <= 0) return true;
+ acc += buffer.toString(
+ encoding, 0, Math.min(n,buffer.length)
+ );
+ n -= buffer.length;
+ });
+ return acc;
+ } else {
+ // If no 'encoding' is specified, then return a Buffer.
+ return self.join(0, n);
+ }
+ };
+
+ // The entire concatenated buffer as a string.
+ self.toString = function () {
+ return self.take('binary');
+ };
+}
+require('util').inherits(BufferList, EventEmitter);