Click here to Skip to main content
11,705,208 members (56,246 online)
Click here to Skip to main content
Articles » Web Development » Node.js » General » Downloads
Add your own
alternative version

Node.Js And Stuff

, 11 Feb 2013 CPOL 98.8K 1.7K 149
Small demo app using Node.Js/Socket.IO/MongoDB/D3.Js and jQuery.
WebSocketDemo.zip
WebSocketDemo
node_modules
.bin
express
.npmignore
.travis.yml
History.md
lib
router
node_modules
commander
.npmignore
.travis.yml
History.md
lib
package.json
Readme.md
connect
.npmignore
lib
middleware
session
public
favicon.ico
icons
page.png
page_add.png
page_attach.png
page_code.png
page_copy.png
page_delete.png
page_edit.png
page_error.png
page_excel.png
page_find.png
page_gear.png
page_go.png
page_green.png
page_key.png
page_lightning.png
page_link.png
page_paintbrush.png
page_paste.png
page_red.png
page_refresh.png
page_save.png
page_white.png
page_white_acrobat.png
page_white_actionscript.png
page_white_add.png
page_white_c.png
page_white_camera.png
page_white_cd.png
page_white_code.png
page_white_code_red.png
page_white_coldfusion.png
page_white_compressed.png
page_white_copy.png
page_white_cplusplus.png
page_white_csharp.png
page_white_cup.png
page_white_database.png
page_white_delete.png
page_white_dvd.png
page_white_edit.png
page_white_error.png
page_white_excel.png
page_white_find.png
page_white_flash.png
page_white_freehand.png
page_white_gear.png
page_white_get.png
page_white_go.png
page_white_h.png
page_white_horizontal.png
page_white_key.png
page_white_lightning.png
page_white_link.png
page_white_magnify.png
page_white_medal.png
page_white_office.png
page_white_paint.png
page_white_paintbrush.png
page_white_paste.png
page_white_php.png
page_white_picture.png
page_white_powerpoint.png
page_white_put.png
page_white_ruby.png
page_white_stack.png
page_white_star.png
page_white_swoosh.png
page_white_text.png
page_white_text_width.png
page_white_tux.png
page_white_vector.png
page_white_visualstudio.png
page_white_width.png
page_white_word.png
page_white_world.png
page_white_wrench.png
page_white_zip.png
page_word.png
page_world.png
node_modules
bytes
.npmignore
component.json
History.md
package.json
Readme.md
formidable
.npmignore
.travis.yml
benchmark
example
lib
node-gently
example
lib
gently
package.json
Readme.md
test
simple
package.json
Readme.md
test
fixture
file
http
special-chars-in-filename
info.md
js
integration
legacy
integration
simple
system
unit
tool
pause
.npmignore
History.md
package.json
Readme.md
qs
.gitmodules
.npmignore
.travis.yml
History.md
lib
package.json
Readme.md
test
mocha.opts
package.json
Readme.md
cookie
.npmignore
.travis.yml
package.json
README.md
test
mocha.opts
crc
.gitmodules
.npmignore
lib
package.json
README.md
test
debug
.npmignore
example
History.md
lib
package.json
Readme.md
fresh
.npmignore
package.json
Readme.md
methods
package.json
mkdirp
.gitignore.orig
.gitignore.rej
.npmignore
.travis.yml
examples
pow.js.orig
pow.js.rej
package.json
README.markdown
test
range-parser
.npmignore
History.md
package.json
Readme.md
send
.npmignore
History.md
lib
node_modules
mime
package.json
README.md
types
mime.types
node.types
package.json
Readme.md
package.json
Readme.md
jade
.npmignore
jade.md
lib
nodes
node_modules
commander
.npmignore
.travis.yml
History.md
lib
package.json
Readme.md
mkdirp
.npmignore
.travis.yml
examples
package.json
README.markdown
test
package.json
Readme.md
test.jade
testing
head.jade
index.jade
layout.jade
user.jade
mongodb
.travis.yml
CONTRIBUTING.md
lib
mongodb
commands
connection
strategies
gridfs
responses
node_modules
bson
.travis.yml
benchmarks
binding.gyp
build
binding.Makefile
bson.target.mk
config.gypi
Release
.deps
Release
bson.node.d
obj.target
bson
ext
bson.o.d
bson.node
linker.lock
obj.target
bson
ext
bson.o
ext
bson.cc
win32
ia32
bson.node
x64
bson.node
lib
bson
package.json
README.md
test
browser
node
data
test_gs_weird_bug.png
tools
tools
jasmine-1.1.0
jasmine_favicon.png
MIT.LICENSE
package.json
Readme.md
node-static
.npmignore
benchmark
bin
etc
trainwreck.jpg
examples
lib
node-static
node_modules
colors
package.json
ReadMe.md
optimist
.travis.yml
example
node_modules
wordwrap
.npmignore
example
package.json
README.markdown
test
package.json
README.markdown
test
_
package.json
README.md
test
fixtures
integration
socket.io
.npmignore
.travis.yml
benchmarks
History.md
lib
stores
transports
websocket
node_modules
policyfile
.npmignore
doc
examples
lib
package.json
README.md
tests
ssl
ssl.crt
ssl.private.key
redis
.npmignore
benches
stress
pubsub
rpushblpop
speed
size-rate.png
changelog.md
examples
lib
parser
package.json
README.md
socket.io-client
.npmignore
bin
dist
WebSocketMain.swf
WebSocketMainInsecure.swf
History.md
lib
transports
vendor
web-socket-js
.npmignore
flash-src
build.sh
com
adobe
net
proxies
RFC2817Socket.as
gsolo
encryption
MD5.as
hurlant
crypto
cert
MozillaRootCertificates.as
X509Certificate.as
X509CertificateCollection.as
Crypto.as
hash
HMAC.as
IHash.as
IHMAC.as
MAC.as
MD2.as
MD5.as
SHA1.as
SHA224.as
SHA256.as
SHABase.as
prng
ARC4.as
IPRNG.as
Random.as
TLSPRF.as
rsa
RSAKey.as
symmetric
AESKey.as
aeskey.pl
BlowFishKey.as
CBCMode.as
CFB8Mode.as
CFBMode.as
CTRMode.as
DESKey.as
ECBMode.as
ICipher.as
IMode.as
IPad.as
IStreamCipher.as
ISymmetricKey.as
IVMode.as
NullPad.as
OFBMode.as
PKCS5.as
SimpleIVMode.as
SSLPad.as
TLSPad.as
TripleDESKey.as
XTeaKey.as
tests
AESKeyTest.as
ARC4Test.as
BigIntegerTest.as
BlowFishKeyTest.as
CBCModeTest.as
CFB8ModeTest.as
CFBModeTest.as
CTRModeTest.as
DESKeyTest.as
ECBModeTest.as
HMACTest.as
ITestHarness.as
MD2Test.as
MD5Test.as
OFBModeTest.as
RSAKeyTest.as
SHA1Test.as
SHA224Test.as
SHA256Test.as
TestCase.as
TLSPRFTest.as
TripleDESKeyTest.as
XTeaKeyTest.as
tls
BulkCiphers.as
CipherSuites.as
IConnectionState.as
ISecurityParameters.as
KeyExchanges.as
MACs.as
SSLConnectionState.as
SSLEvent.as
SSLSecurityParameters.as
TLSConfig.as
TLSConnectionState.as
TLSEngine.as
TLSError.as
TLSEvent.as
TLSSecurityParameters.as
TLSSocket.as
TLSSocketEvent.as
TLSTest.as
math
BarrettReduction.as
bi_internal.as
BigInteger.as
ClassicReduction.as
IReduction.as
MontgomeryReduction.as
NullReduction.as
util
ArrayUtil.as
Base64.as
der
ByteString.as
DER.as
IAsn1Type.as
Integer.as
ObjectIdentifier.as
OID.as
PEM.as
PrintableString.as
Sequence.as
Set.as
Type.as
UTCTime.as
Hex.as
Memory.as
IWebSocketLogger.as
WebSocket.as
WebSocketEvent.as
WebSocketMain.as
WebSocketMainInsecure.as
README.md
WebSocketMain.swf
WebSocketMainInsecure.zip
node_modules
.bin
active-x-obfuscator
.npmignore
node_modules
zeparser
.npmignore
package.json
package.json
Readme.md
uglify-js
.npmignore
lib
package.json
package.json~
README.org
test
unit
compress
expected
test
tmp
ws
.npmignore
.travis.yml
bench
binding.gyp
doc
ws.md
examples
fileapi
.npmignore
package.json
public
serverstats
package.json
public
serverstats-express_3
package.json
public
History.md
lib
node_modules
commander
.npmignore
.travis.yml
History.md
lib
package.json
Readme.md
options
.npmignore
lib
package.json
README.md
test
fixtures
test.conf
tinycolor
.npmignore
package.json
README.md
package.json
README.md
src
bufferutil.cc
validation.cc
test
fixtures
certificate.pem
key.pem
request.pem
xmlhttprequest
autotest.watchr
example
lib
package.json
README.md
tests
package.json
README.md
test
node
package.json
Readme.md
stylus
lib
convert
functions
index.styl
nodes
stack
visitor
node_modules
cssom
.gitmodules
.npmignore
lib
package.json
README.mdown
debug
.npmignore
example
History.md
lib
package.json
Readme.md
mkdirp
.npmignore
.travis.yml
examples
package.json
README.markdown
test
package.json
Readme.md
testing
small.styl
test.styl
package.json
public
images
Friend.png
Header.pdn
Header.png
javascripts
jquery-ui-1.9.1.custom
css
ui-lightness
images
ui-bg_diagonals-thick_18_b81900_40x40.png
ui-bg_diagonals-thick_20_666666_40x40.png
ui-bg_flat_10_000000_40x100.png
ui-bg_glass_100_f6f6f6_1x400.png
ui-bg_glass_100_fdf5ce_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_gloss-wave_35_f6a828_500x100.png
ui-bg_highlight-soft_100_eeeeee_1x100.png
ui-bg_highlight-soft_75_ffe45c_1x100.png
ui-icons_222222_256x240.png
ui-icons_228ef1_256x240.png
ui-icons_ef8c08_256x240.png
ui-icons_ffd27a_256x240.png
ui-icons_ffffff_256x240.png
js
stylesheets
home.styl
style.styl
routes
views
d3demo.jade
home.jade
layout.jade
/*!
 * socket.io-node
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var fs = require('fs')
  , url = require('url')
  , tty = require('tty')
  , crypto = require('crypto')
  , util = require('./util')
  , store = require('./store')
  , client = require('socket.io-client')
  , transports = require('./transports')
  , Logger = require('./logger')
  , Socket = require('./socket')
  , MemoryStore = require('./stores/memory')
  , SocketNamespace = require('./namespace')
  , Static = require('./static')
  , EventEmitter = process.EventEmitter;

/**
 * Export the constructor.
 */

exports = module.exports = Manager;

/**
 * Default transports.
 */

var defaultTransports = exports.defaultTransports = [
    'websocket'
  , 'htmlfile'
  , 'xhr-polling'
  , 'jsonp-polling'
];

/**
 * Inherited defaults.
 */

var parent = module.parent.exports
  , protocol = parent.protocol
  , jsonpolling_re = /^\d+$/;

/**
 * Manager constructor.
 *
 * @param {HTTPServer} server
 * @param {Object} options, optional
 * @api public
 */

function Manager (server, options) {
  this.server = server;
  this.namespaces = {};
  this.sockets = this.of('');
  this.settings = {
      origins: '*:*'
    , log: true
    , store: new MemoryStore
    , logger: new Logger
    , static: new Static(this)
    , heartbeats: true
    , resource: '/socket.io'
    , transports: defaultTransports
    , authorization: false
    , blacklist: ['disconnect']
    , 'log level': 3
    , 'log colors': tty.isatty(process.stdout.fd)
    , 'close timeout': 60
    , 'heartbeat interval': 25
    , 'heartbeat timeout': 60
    , 'polling duration': 20
    , 'flash policy server': true
    , 'flash policy port': 10843
    , 'destroy upgrade': true
    , 'destroy buffer size': 10E7
    , 'browser client': true
    , 'browser client cache': true
    , 'browser client minification': false
    , 'browser client etag': false
    , 'browser client expires': 315360000
    , 'browser client gzip': false
    , 'browser client handler': false
    , 'client store expiration': 15
    , 'match origin protocol': false
  };

  for (var i in options) {
    if (options.hasOwnProperty(i)) {
      this.settings[i] = options[i];
    }
  }

  var self = this;

  // default error handler
  server.on('error', function(err) {
    self.log.warn('error raised: ' + err);
  });

  this.initStore();

  this.on('set:store', function() {
    self.initStore();
  });

  // reset listeners
  this.oldListeners = server.listeners('request').splice(0);

  server.on('request', function (req, res) {
    self.handleRequest(req, res);
  });

  server.on('upgrade', function (req, socket, head) {
    self.handleUpgrade(req, socket, head);
  });

  server.on('close', function () {
    clearInterval(self.gc);
  });

  server.once('listening', function () {
    self.gc = setInterval(self.garbageCollection.bind(self), 10000);
  });

  for (var i in transports) {
    if (transports.hasOwnProperty(i)) {
      if (transports[i].init) {
        transports[i].init(this);
      }
    }
  }

  // forward-compatibility with 1.0
  var self = this;
  this.sockets.on('connection', function (conn) {
    self.emit('connection', conn);
  });

  this.sequenceNumber = Date.now() | 0;
 
  this.log.info('socket.io started');
};

Manager.prototype.__proto__ = EventEmitter.prototype

/**
 * Store accessor shortcut.
 *
 * @api public
 */

Manager.prototype.__defineGetter__('store', function () {
  var store = this.get('store');
  store.manager = this;
  return store;
});

/**
 * Logger accessor.
 *
 * @api public
 */

Manager.prototype.__defineGetter__('log', function () {
  var logger = this.get('logger');

  logger.level = this.get('log level') || -1;
  logger.colors = this.get('log colors');
  logger.enabled = this.enabled('log');

  return logger;
});

/**
 * Static accessor.
 *
 * @api public
 */

Manager.prototype.__defineGetter__('static', function () {
  return this.get('static');
});

/**
 * Get settings.
 *
 * @api public
 */

Manager.prototype.get = function (key) {
  return this.settings[key];
};

/**
 * Set settings
 *
 * @api public
 */

Manager.prototype.set = function (key, value) {
  if (arguments.length == 1) return this.get(key);
  this.settings[key] = value;
  this.emit('set:' + key, this.settings[key], key);
  return this;
};

/**
 * Enable a setting
 *
 * @api public
 */

Manager.prototype.enable = function (key) {
  this.settings[key] = true;
  this.emit('set:' + key, this.settings[key], key);
  return this;
};

/**
 * Disable a setting
 *
 * @api public
 */

Manager.prototype.disable = function (key) {
  this.settings[key] = false;
  this.emit('set:' + key, this.settings[key], key);
  return this;
};

/**
 * Checks if a setting is enabled
 *
 * @api public
 */

Manager.prototype.enabled = function (key) {
  return !!this.settings[key];
};

/**
 * Checks if a setting is disabled
 *
 * @api public
 */

Manager.prototype.disabled = function (key) {
  return !this.settings[key];
};

/**
 * Configure callbacks.
 *
 * @api public
 */

Manager.prototype.configure = function (env, fn) {
  if ('function' == typeof env) {
    env.call(this);
  } else if (env == (process.env.NODE_ENV || 'development')) {
    fn.call(this);
  }

  return this;
};

/**
 * Initializes everything related to the message dispatcher.
 *
 * @api private
 */

Manager.prototype.initStore = function () {
  this.handshaken = {};
  this.connected = {};
  this.open = {};
  this.closed = {};
  this.rooms = {};
  this.roomClients = {};

  var self = this;

  this.store.subscribe('handshake', function (id, data) {
    self.onHandshake(id, data);
  });

  this.store.subscribe('connect', function (id) {
    self.onConnect(id);
  });

  this.store.subscribe('open', function (id) {
    self.onOpen(id);
  });

  this.store.subscribe('join', function (id, room) {
    self.onJoin(id, room);
  });

  this.store.subscribe('leave', function (id, room) {
    self.onLeave(id, room);
  });

  this.store.subscribe('close', function (id) {
    self.onClose(id);
  });

  this.store.subscribe('dispatch', function (room, packet, volatile, exceptions) {
    self.onDispatch(room, packet, volatile, exceptions);
  });

  this.store.subscribe('disconnect', function (id) {
    self.onDisconnect(id);
  });
};

/**
 * Called when a client handshakes.
 *
 * @param text
 */

Manager.prototype.onHandshake = function (id, data) {
  this.handshaken[id] = data;
};

/**
 * Called when a client connects (ie: transport first opens)
 *
 * @api private
 */

Manager.prototype.onConnect = function (id) {
  this.connected[id] = true;
};

/**
 * Called when a client opens a request in a different node.
 *
 * @api private
 */

Manager.prototype.onOpen = function (id) {
  this.open[id] = true;

  if (this.closed[id]) {
    var self = this;

    this.store.unsubscribe('dispatch:' + id, function () {
      var transport = self.transports[id];
      if (self.closed[id] && self.closed[id].length && transport) {

        // if we have buffered messages that accumulate between calling
        // onOpen an this async callback, send them if the transport is 
        // still open, otherwise leave them buffered
        if (transport.open) {
          transport.payload(self.closed[id]);
          self.closed[id] = [];
        }
      }
    });
  }

  // clear the current transport
  if (this.transports[id]) {
    this.transports[id].discard();
    this.transports[id] = null;
  }
};

/**
 * Called when a message is sent to a namespace and/or room.
 *
 * @api private
 */

Manager.prototype.onDispatch = function (room, packet, volatile, exceptions) {
  if (this.rooms[room]) {
    for (var i = 0, l = this.rooms[room].length; i < l; i++) {
      var id = this.rooms[room][i];

      if (!~exceptions.indexOf(id)) {
        if (this.transports[id] && this.transports[id].open) {
          this.transports[id].onDispatch(packet, volatile);
        } else if (!volatile) {
          this.onClientDispatch(id, packet);
        }
      }
    }
  }
};

/**
 * Called when a client joins a nsp / room.
 *
 * @api private
 */

Manager.prototype.onJoin = function (id, name) {
  if (!this.roomClients[id]) {
    this.roomClients[id] = {};
  }

  if (!this.rooms[name]) {
    this.rooms[name] = [];
  }

  if (!~this.rooms[name].indexOf(id)) {
    this.rooms[name].push(id);
    this.roomClients[id][name] = true;
  }
};

/**
 * Called when a client leaves a nsp / room.
 *
 * @param private
 */

Manager.prototype.onLeave = function (id, room) {
  if (this.rooms[room]) {
    var index = this.rooms[room].indexOf(id);

    if (index >= 0) {
      this.rooms[room].splice(index, 1);
    }

    if (!this.rooms[room].length) {
      delete this.rooms[room];
    }

    if (this.roomClients[id]) {
      delete this.roomClients[id][room];
    }
  }
};

/**
 * Called when a client closes a request in different node.
 *
 * @api private
 */

Manager.prototype.onClose = function (id) {
  if (this.open[id]) {
    delete this.open[id];
  }

  this.closed[id] = [];

  var self = this;

  this.store.subscribe('dispatch:' + id, function (packet, volatile) {
    if (!volatile) {
      self.onClientDispatch(id, packet);
    }
  });
};

/**
 * Dispatches a message for a closed client.
 *
 * @api private
 */

Manager.prototype.onClientDispatch = function (id, packet) {
  if (this.closed[id]) {
    this.closed[id].push(packet);
  }
};

/**
 * Receives a message for a client.
 *
 * @api private
 */

Manager.prototype.onClientMessage = function (id, packet) {
  if (this.namespaces[packet.endpoint]) {
    this.namespaces[packet.endpoint].handlePacket(id, packet);
  }
};

/**
 * Fired when a client disconnects (not triggered).
 *
 * @api private
 */

Manager.prototype.onClientDisconnect = function (id, reason) {
  for (var name in this.namespaces) {
    if (this.namespaces.hasOwnProperty(name)) {
      this.namespaces[name].handleDisconnect(id, reason, typeof this.roomClients[id] !== 'undefined' &&
        typeof this.roomClients[id][name] !== 'undefined');
    }
  }

  this.onDisconnect(id);
};

/**
 * Called when a client disconnects.
 *
 * @param text
 */

Manager.prototype.onDisconnect = function (id, local) {
  delete this.handshaken[id];

  if (this.open[id]) {
    delete this.open[id];
  }

  if (this.connected[id]) {
    delete this.connected[id];
  }

  if (this.transports[id]) {
    this.transports[id].discard();
    delete this.transports[id];
  }

  if (this.closed[id]) {
    delete this.closed[id];
  }

  if (this.roomClients[id]) {
    for (var room in this.roomClients[id]) {
      if (this.roomClients[id].hasOwnProperty(room)) {
        this.onLeave(id, room);
      }
    }
    delete this.roomClients[id]
  }

  this.store.destroyClient(id, this.get('client store expiration'));

  this.store.unsubscribe('dispatch:' + id);

  if (local) {
    this.store.unsubscribe('message:' + id);
    this.store.unsubscribe('disconnect:' + id);
  }
};

/**
 * Handles an HTTP request.
 *
 * @api private
 */

Manager.prototype.handleRequest = function (req, res) {
  var data = this.checkRequest(req);

  if (!data) {
    for (var i = 0, l = this.oldListeners.length; i < l; i++) {
      this.oldListeners[i].call(this.server, req, res);
    }

    return;
  }

  if (data.static || !data.transport && !data.protocol) {
    if (data.static && this.enabled('browser client')) {
      this.static.write(data.path, req, res);
    } else {
      res.writeHead(200);
      res.end('Welcome to socket.io.');

      this.log.info('unhandled socket.io url');
    }

    return;
  }

  if (data.protocol != protocol) {
    res.writeHead(500);
    res.end('Protocol version not supported.');

    this.log.info('client protocol version unsupported');
  } else {
    if (data.id) {
      this.handleHTTPRequest(data, req, res);
    } else {
      this.handleHandshake(data, req, res);
    }
  }
};

/**
 * Handles an HTTP Upgrade.
 *
 * @api private
 */

Manager.prototype.handleUpgrade = function (req, socket, head) {
  var data = this.checkRequest(req)
    , self = this;

  if (!data) {
    if (this.enabled('destroy upgrade')) {
      socket.end();
      this.log.debug('destroying non-socket.io upgrade');
    }

    return;
  }

  req.head = head;
  this.handleClient(data, req);
};

/**
 * Handles a normal handshaken HTTP request (eg: long-polling)
 *
 * @api private
 */

Manager.prototype.handleHTTPRequest = function (data, req, res) {
  req.res = res;
  this.handleClient(data, req);
};

/**
 * Intantiantes a new client.
 *
 * @api private
 */

Manager.prototype.handleClient = function (data, req) {
  var socket = req.socket
    , store = this.store
    , self = this;

  // handle sync disconnect xhrs
  if (undefined != data.query.disconnect) {
    if (this.transports[data.id] && this.transports[data.id].open) {
      this.transports[data.id].onForcedDisconnect();
    } else {
      this.store.publish('disconnect-force:' + data.id);
    }
    req.res.writeHead(200);
    req.res.end();
    return;
  }

  if (!~this.get('transports').indexOf(data.transport)) {
    this.log.warn('unknown transport: "' + data.transport + '"');
    req.connection.end();
    return;
  }

  var transport = new transports[data.transport](this, data, req)
    , handshaken = this.handshaken[data.id];

  if (transport.disconnected) {
    // failed during transport setup
    req.connection.end();
    return;
  }
  if (handshaken) {
    if (transport.open) {
      if (this.closed[data.id] && this.closed[data.id].length) {
        transport.payload(this.closed[data.id]);
        this.closed[data.id] = [];
      }

      this.onOpen(data.id);
      this.store.publish('open', data.id);
      this.transports[data.id] = transport;
    }

    if (!this.connected[data.id]) {
      this.onConnect(data.id);
      this.store.publish('connect', data.id);

      // flag as used
      delete handshaken.issued;
      this.onHandshake(data.id, handshaken);
      this.store.publish('handshake', data.id, handshaken);

      // initialize the socket for all namespaces
      for (var i in this.namespaces) {
        if (this.namespaces.hasOwnProperty(i)) {
          var socket = this.namespaces[i].socket(data.id, true);

          // echo back connect packet and fire connection event
          if (i === '') {
            this.namespaces[i].handlePacket(data.id, { type: 'connect' });
          }
        }
      }

      this.store.subscribe('message:' + data.id, function (packet) {
        self.onClientMessage(data.id, packet);
      });

      this.store.subscribe('disconnect:' + data.id, function (reason) {
        self.onClientDisconnect(data.id, reason);
      });
    }
  } else {
    if (transport.open) {
      transport.error('client not handshaken', 'reconnect');
    }

    transport.discard();
  }
};

/**
 * Generates a session id.
 *
 * @api private
 */

Manager.prototype.generateId = function () {
  var rand = new Buffer(15); // multiple of 3 for base64
  if (!rand.writeInt32BE) {
    return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
      + Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
  }
  this.sequenceNumber = (this.sequenceNumber + 1) | 0;
  rand.writeInt32BE(this.sequenceNumber, 11);
  if (crypto.randomBytes) {
    crypto.randomBytes(12).copy(rand);
  } else {
    // not secure for node 0.4
    [0, 4, 8].forEach(function(i) {
      rand.writeInt32BE(Math.random() * Math.pow(2, 32) | 0, i);
    });
  }
  return rand.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
};

/**
 * Handles a handshake request.
 *
 * @api private
 */

Manager.prototype.handleHandshake = function (data, req, res) {
  var self = this
    , origin = req.headers.origin
    , headers = {
        'Content-Type': 'text/plain'
    };

  function writeErr (status, message) {
    if (data.query.jsonp && jsonpolling_re.test(data.query.jsonp)) {
      res.writeHead(200, { 'Content-Type': 'application/javascript' });
      res.end('io.j[' + data.query.jsonp + '](new Error("' + message + '"));');
    } else {
      res.writeHead(status, headers);
      res.end(message);
    }
  };

  function error (err) {
    writeErr(500, 'handshake error');
    self.log.warn('handshake error ' + err);
  };

  if (!this.verifyOrigin(req)) {
    writeErr(403, 'handshake bad origin');
    return;
  }

  var handshakeData = this.handshakeData(data);

  if (origin) {
    // https://developer.mozilla.org/En/HTTP_Access_Control
    headers['Access-Control-Allow-Origin'] = origin;
    headers['Access-Control-Allow-Credentials'] = 'true';
  }

  this.authorize(handshakeData, function (err, authorized, newData) {
    if (err) return error(err);

    if (authorized) {
      var id = self.generateId()
        , hs = [
              id
            , self.enabled('heartbeats') ? self.get('heartbeat timeout') || '' : ''
            , self.get('close timeout') || ''
            , self.transports(data).join(',')
          ].join(':');

      if (data.query.jsonp && jsonpolling_re.test(data.query.jsonp)) {
        hs = 'io.j[' + data.query.jsonp + '](' + JSON.stringify(hs) + ');';
        res.writeHead(200, { 'Content-Type': 'application/javascript' });
      } else {
        res.writeHead(200, headers);
      }

      res.end(hs);

      self.onHandshake(id, newData || handshakeData);
      self.store.publish('handshake', id, newData || handshakeData);

      self.log.info('handshake authorized', id);
    } else {
      writeErr(403, 'handshake unauthorized');
      self.log.info('handshake unauthorized');
    }
  })
};

/**
 * Gets normalized handshake data
 *
 * @api private
 */

Manager.prototype.handshakeData = function (data) {
  var connection = data.request.connection
    , connectionAddress
    , date = new Date;

  if (connection.remoteAddress) {
    connectionAddress = {
        address: connection.remoteAddress
      , port: connection.remotePort
    };
  } else if (connection.socket && connection.socket.remoteAddress) {
    connectionAddress = {
        address: connection.socket.remoteAddress
      , port: connection.socket.remotePort
    };
  }

  return {
      headers: data.headers
    , address: connectionAddress
    , time: date.toString()
    , query: data.query
    , url: data.request.url
    , xdomain: !!data.request.headers.origin
    , secure: data.request.connection.secure
    , issued: +date
  };
};

/**
 * Verifies the origin of a request.
 *
 * @api private
 */

Manager.prototype.verifyOrigin = function (request) {
  var origin = request.headers.origin || request.headers.referer
    , origins = this.get('origins');

  if (origin === 'null') origin = '*';

  if (origins.indexOf('*:*') !== -1) {
    return true;
  }

  if (origin) {
    try {
      var parts = url.parse(origin);
      parts.port = parts.port || 80;
      var ok =
        ~origins.indexOf(parts.hostname + ':' + parts.port) ||
        ~origins.indexOf(parts.hostname + ':*') ||
        ~origins.indexOf('*:' + parts.port);
      if (!ok) this.log.warn('illegal origin: ' + origin);
      return ok;
    } catch (ex) {
      this.log.warn('error parsing origin');
    }
  }
  else {
    this.log.warn('origin missing from handshake, yet required by config');
  }
  return false;
};

/**
 * Handles an incoming packet.
 *
 * @api private
 */

Manager.prototype.handlePacket = function (sessid, packet) {
  this.of(packet.endpoint || '').handlePacket(sessid, packet);
};

/**
 * Performs authentication.
 *
 * @param Object client request data
 * @api private
 */

Manager.prototype.authorize = function (data, fn) {
  if (this.get('authorization')) {
    var self = this;

    this.get('authorization').call(this, data, function (err, authorized) {
      self.log.debug('client ' + authorized ? 'authorized' : 'unauthorized');
      fn(err, authorized);
    });
  } else {
    this.log.debug('client authorized');
    fn(null, true);
  }

  return this;
};

/**
 * Retrieves the transports adviced to the user.
 *
 * @api private
 */

Manager.prototype.transports = function (data) {
  var transp = this.get('transports')
    , ret = [];

  for (var i = 0, l = transp.length; i < l; i++) {
    var transport = transp[i];

    if (transport) {
      if (!transport.checkClient || transport.checkClient(data)) {
        ret.push(transport);
      }
    }
  }

  return ret;
};

/**
 * Checks whether a request is a socket.io one.
 *
 * @return {Object} a client request data object or `false`
 * @api private
 */

var regexp = /^\/([^\/]+)\/?([^\/]+)?\/?([^\/]+)?\/?$/

Manager.prototype.checkRequest = function (req) {
  var resource = this.get('resource');

  var match;
  if (typeof resource === 'string') {
    match = req.url.substr(0, resource.length);
    if (match !== resource) match = null;
  } else {
    match = resource.exec(req.url);
    if (match) match = match[0];
  }

  if (match) {
    var uri = url.parse(req.url.substr(match.length), true)
      , path = uri.pathname || ''
      , pieces = path.match(regexp);

    // client request data
    var data = {
        query: uri.query || {}
      , headers: req.headers
      , request: req
      , path: path
    };

    if (pieces) {
      data.protocol = Number(pieces[1]);
      data.transport = pieces[2];
      data.id = pieces[3];
      data.static = !!this.static.has(path);
    };

    return data;
  }

  return false;
};

/**
 * Declares a socket namespace
 *
 * @api public
 */

Manager.prototype.of = function (nsp) {
  if (this.namespaces[nsp]) {
    return this.namespaces[nsp];
  }

  return this.namespaces[nsp] = new SocketNamespace(this, nsp);
};

/**
 * Perform garbage collection on long living objects and properties that cannot
 * be removed automatically.
 *
 * @api private
 */

Manager.prototype.garbageCollection = function () {
  // clean up unused handshakes
  var ids = Object.keys(this.handshaken)
    , i = ids.length
    , now = Date.now()
    , handshake;

  while (i--) {
    handshake = this.handshaken[ids[i]];

    if ('issued' in handshake && (now - handshake.issued) >= 3E4) {
      this.onDisconnect(ids[i]);
    }
  }
};

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sacha Barber
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150819.1 | Last Updated 11 Feb 2013
Article Copyright 2013 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid