Permalink
Browse files

Fixed encoding for WebSocket (set to utf-8 per spec)

Fixed handling of chunks sent by UA
  • Loading branch information...
rauchg committed Apr 4, 2010
1 parent 4e58204 commit bf9ba8c08bb725f876101fc6c96a31ef9bf7b93c
Showing with 29 additions and 17 deletions.
  1. +29 −17 lib/socket.io/transports/websocket.js
@@ -1,12 +1,12 @@
var Client = require('../client').Client,
- url = require('url'),
- sys = require('sys');
+ url = require('url');
this.websocket = Client.extend({
- _onConnect: function(req, res){
+ _onConnect: function(req, res){
var self = this;
- this.__super__(req, res);
+ this.__super__(req, res);
+ this.data = '';
if (this.request.headers['connection'] !== 'Upgrade'
|| this.request.headers['upgrade'] !== 'WebSocket'
@@ -20,32 +20,44 @@ this.websocket = Client.extend({
if (!('hijack' in self.connection)){
throw new Error('You have to patch Node! Please refer to the README');
}
-
+
self.connection.hijack();
self.connection.setTimeout(0);
+ self.connection.setEncoding('utf8');
self.connection.setNoDelay(true);
- self.connection.addListener('end', function(){ self._onClose(); });
- self.connection.addListener('data', function(data){
- if (data[0] !== '\u0000' && data[data.length - 1] !== '\ufffd'){
- self.connection.close();
- } else {
- self._onMessage(data.substr(1, data.length - 2));
- }
- });
+ self.connection.addListener('end', function(){ self._onClose(); });
+ self.connection.addListener('data', function(data){ self._handle(data); });
});
this.response.use_chunked_encoding_by_default = false;
- this.response.writeHeader(101, 'Web Socket Protocol Handshake', {
+ this.response.writeHeader(101, 'Web Socket Protocol Handshake', {
'Upgrade': 'WebSocket',
'Connection': 'Upgrade',
'WebSocket-Origin': this.request.headers.origin,
'WebSocket-Location': 'ws://' + this.request.headers.host + this.request.url
- });
- this.response.flush();
-
+ });
+ this.response.flush();
this._payload();
},
+ _handle: function(data){
+ this.data += data;
+ chunks = this.data.split('\ufffd');
+ chunk_count = chunks.length - 1;
+ for (var i = 0; i < chunk_count; i++) {
+ chunk = chunks[i];
+ if (chunk[0] != '\u0000') {
+ this.listener.options.log('Data incorrectly framed by UA. Dropping connection');
+ this.connection.close();
+ return false;
+ }
+
+ this._onMessage(chunk.slice(1));
+ }
+
+ this.data = chunks[chunks.length - 1];
+ },
+
_verifyOrigin: function(origin){
var parts = url.parse(origin);
return this.listener.options.origins.indexOf('*:*') !== -1

0 comments on commit bf9ba8c

Please sign in to comment.