3 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
11 var fs = require('fs')
12 , url = require('url')
13 , tty = require('tty')
14 , crypto = require('crypto')
15 , util = require('./util')
16 , store = require('./store')
17 , client = require('socket.io-client')
18 , transports = require('./transports')
19 , Logger = require('./logger')
20 , Socket = require('./socket')
21 , MemoryStore = require('./stores/memory')
22 , SocketNamespace = require('./namespace')
23 , Static = require('./static')
24 , EventEmitter = process.EventEmitter;
27 * Export the constructor.
30 exports = module.exports = Manager;
36 var defaultTransports = exports.defaultTransports = [
47 var parent = module.parent.exports
48 , protocol = parent.protocol
49 , jsonpolling_re = /^\d+$/;
52 * Manager constructor.
54 * @param {HTTPServer} server
55 * @param {Object} options, optional
59 function Manager (server, options) {
62 this.sockets = this.of('');
66 , store: new MemoryStore
68 , static: new Static(this)
70 , resource: '/socket.io'
71 , transports: defaultTransports
72 , authorization: false
73 , blacklist: ['disconnect']
75 , 'log colors': tty.isatty(process.stdout.fd)
77 , 'heartbeat interval': 25
78 , 'heartbeat timeout': 60
79 , 'polling duration': 20
80 , 'flash policy server': true
81 , 'flash policy port': 10843
82 , 'destroy upgrade': true
83 , 'destroy buffer size': 10E7
84 , 'browser client': true
85 , 'browser client cache': true
86 , 'browser client minification': false
87 , 'browser client etag': false
88 , 'browser client expires': 315360000
89 , 'browser client gzip': false
90 , 'browser client handler': false
91 , 'client store expiration': 15
92 , 'match origin protocol': false
95 for (var i in options) {
96 if (options.hasOwnProperty(i)) {
97 this.settings[i] = options[i];
103 // default error handler
104 server.on('error', function(err) {
105 self.log.warn('error raised: ' + err);
110 this.on('set:store', function() {
115 this.oldListeners = server.listeners('request').splice(0);
116 server.removeAllListeners('request');
118 server.on('request', function (req, res) {
119 self.handleRequest(req, res);
122 server.on('upgrade', function (req, socket, head) {
123 self.handleUpgrade(req, socket, head);
126 server.on('close', function () {
127 clearInterval(self.gc);
130 server.once('listening', function () {
131 self.gc = setInterval(self.garbageCollection.bind(self), 10000);
134 for (var i in transports) {
135 if (transports.hasOwnProperty(i)) {
136 if (transports[i].init) {
137 transports[i].init(this);
142 // forward-compatibility with 1.0
144 this.sockets.on('connection', function (conn) {
145 self.emit('connection', conn);
148 this.sequenceNumber = Date.now() | 0;
150 this.log.info('socket.io started');
153 Manager.prototype.__proto__ = EventEmitter.prototype
156 * Store accessor shortcut.
161 Manager.prototype.__defineGetter__('store', function () {
162 var store = this.get('store');
163 store.manager = this;
173 Manager.prototype.__defineGetter__('log', function () {
174 var logger = this.get('logger');
176 logger.level = this.get('log level') || -1;
177 logger.colors = this.get('log colors');
178 logger.enabled = this.enabled('log');
189 Manager.prototype.__defineGetter__('static', function () {
190 return this.get('static');
199 Manager.prototype.get = function (key) {
200 return this.settings[key];
209 Manager.prototype.set = function (key, value) {
210 if (arguments.length == 1) return this.get(key);
211 this.settings[key] = value;
212 this.emit('set:' + key, this.settings[key], key);
222 Manager.prototype.enable = function (key) {
223 this.settings[key] = true;
224 this.emit('set:' + key, this.settings[key], key);
234 Manager.prototype.disable = function (key) {
235 this.settings[key] = false;
236 this.emit('set:' + key, this.settings[key], key);
241 * Checks if a setting is enabled
246 Manager.prototype.enabled = function (key) {
247 return !!this.settings[key];
251 * Checks if a setting is disabled
256 Manager.prototype.disabled = function (key) {
257 return !this.settings[key];
261 * Configure callbacks.
266 Manager.prototype.configure = function (env, fn) {
267 if ('function' == typeof env) {
269 } else if (env == (process.env.NODE_ENV || 'development')) {
277 * Initializes everything related to the message dispatcher.
282 Manager.prototype.initStore = function () {
283 this.handshaken = {};
288 this.roomClients = {};
292 this.store.subscribe('handshake', function (id, data) {
293 self.onHandshake(id, data);
296 this.store.subscribe('connect', function (id) {
300 this.store.subscribe('open', function (id) {
304 this.store.subscribe('join', function (id, room) {
305 self.onJoin(id, room);
308 this.store.subscribe('leave', function (id, room) {
309 self.onLeave(id, room);
312 this.store.subscribe('close', function (id) {
316 this.store.subscribe('dispatch', function (room, packet, volatile, exceptions) {
317 self.onDispatch(room, packet, volatile, exceptions);
320 this.store.subscribe('disconnect', function (id) {
321 self.onDisconnect(id);
326 * Called when a client handshakes.
331 Manager.prototype.onHandshake = function (id, data) {
332 this.handshaken[id] = data;
336 * Called when a client connects (ie: transport first opens)
341 Manager.prototype.onConnect = function (id) {
342 this.connected[id] = true;
346 * Called when a client opens a request in a different node.
351 Manager.prototype.onOpen = function (id) {
352 this.open[id] = true;
354 if (this.closed[id]) {
357 this.store.unsubscribe('dispatch:' + id, function () {
358 var transport = self.transports[id];
359 if (self.closed[id] && self.closed[id].length && transport) {
361 // if we have buffered messages that accumulate between calling
362 // onOpen an this async callback, send them if the transport is
363 // still open, otherwise leave them buffered
364 if (transport.open) {
365 transport.payload(self.closed[id]);
366 self.closed[id] = [];
372 // clear the current transport
373 if (this.transports[id]) {
374 this.transports[id].discard();
375 this.transports[id] = null;
380 * Called when a message is sent to a namespace and/or room.
385 Manager.prototype.onDispatch = function (room, packet, volatile, exceptions) {
386 if (this.rooms[room]) {
387 for (var i = 0, l = this.rooms[room].length; i < l; i++) {
388 var id = this.rooms[room][i];
390 if (!~exceptions.indexOf(id)) {
391 if (this.transports[id] && this.transports[id].open) {
392 this.transports[id].onDispatch(packet, volatile);
393 } else if (!volatile) {
394 this.onClientDispatch(id, packet);
402 * Called when a client joins a nsp / room.
407 Manager.prototype.onJoin = function (id, name) {
408 if (!this.roomClients[id]) {
409 this.roomClients[id] = {};
412 if (!this.rooms[name]) {
413 this.rooms[name] = [];
416 if (!~this.rooms[name].indexOf(id)) {
417 this.rooms[name].push(id);
418 this.roomClients[id][name] = true;
423 * Called when a client leaves a nsp / room.
428 Manager.prototype.onLeave = function (id, room) {
429 if (this.rooms[room]) {
430 var index = this.rooms[room].indexOf(id);
433 this.rooms[room].splice(index, 1);
436 if (!this.rooms[room].length) {
437 delete this.rooms[room];
440 if (this.roomClients[id]) {
441 delete this.roomClients[id][room];
447 * Called when a client closes a request in different node.
452 Manager.prototype.onClose = function (id) {
454 delete this.open[id];
457 this.closed[id] = [];
461 this.store.subscribe('dispatch:' + id, function (packet, volatile) {
463 self.onClientDispatch(id, packet);
469 * Dispatches a message for a closed client.
474 Manager.prototype.onClientDispatch = function (id, packet) {
475 if (this.closed[id]) {
476 this.closed[id].push(packet);
481 * Receives a message for a client.
486 Manager.prototype.onClientMessage = function (id, packet) {
487 if (this.namespaces[packet.endpoint]) {
488 this.namespaces[packet.endpoint].handlePacket(id, packet);
493 * Fired when a client disconnects (not triggered).
498 Manager.prototype.onClientDisconnect = function (id, reason) {
499 for (var name in this.namespaces) {
500 if (this.namespaces.hasOwnProperty(name)) {
501 this.namespaces[name].handleDisconnect(id, reason, typeof this.roomClients[id] !== 'undefined' &&
502 typeof this.roomClients[id][name] !== 'undefined');
506 this.onDisconnect(id);
510 * Called when a client disconnects.
515 Manager.prototype.onDisconnect = function (id, local) {
516 delete this.handshaken[id];
519 delete this.open[id];
522 if (this.connected[id]) {
523 delete this.connected[id];
526 if (this.transports[id]) {
527 this.transports[id].discard();
528 delete this.transports[id];
531 if (this.closed[id]) {
532 delete this.closed[id];
535 if (this.roomClients[id]) {
536 for (var room in this.roomClients[id]) {
537 if (this.roomClients[id].hasOwnProperty(room)) {
538 this.onLeave(id, room);
541 delete this.roomClients[id]
544 this.store.destroyClient(id, this.get('client store expiration'));
546 this.store.unsubscribe('dispatch:' + id);
549 this.store.unsubscribe('message:' + id);
550 this.store.unsubscribe('disconnect:' + id);
555 * Handles an HTTP request.
560 Manager.prototype.handleRequest = function (req, res) {
561 var data = this.checkRequest(req);
564 for (var i = 0, l = this.oldListeners.length; i < l; i++) {
565 this.oldListeners[i].call(this.server, req, res);
571 if (data.static || !data.transport && !data.protocol) {
572 if (data.static && this.enabled('browser client')) {
573 this.static.write(data.path, req, res);
576 res.end('Welcome to socket.io.');
578 this.log.info('unhandled socket.io url');
584 if (data.protocol != protocol) {
586 res.end('Protocol version not supported.');
588 this.log.info('client protocol version unsupported');
591 this.handleHTTPRequest(data, req, res);
593 this.handleHandshake(data, req, res);
599 * Handles an HTTP Upgrade.
604 Manager.prototype.handleUpgrade = function (req, socket, head) {
605 var data = this.checkRequest(req)
609 if (this.enabled('destroy upgrade')) {
611 this.log.debug('destroying non-socket.io upgrade');
618 this.handleClient(data, req);
623 * Handles a normal handshaken HTTP request (eg: long-polling)
628 Manager.prototype.handleHTTPRequest = function (data, req, res) {
630 this.handleClient(data, req);
634 * Intantiantes a new client.
639 Manager.prototype.handleClient = function (data, req) {
640 var socket = req.socket
644 // handle sync disconnect xhrs
645 if (undefined != data.query.disconnect) {
646 if (this.transports[data.id] && this.transports[data.id].open) {
647 this.transports[data.id].onForcedDisconnect();
649 this.store.publish('disconnect-force:' + data.id);
651 req.res.writeHead(200);
656 if (!~this.get('transports').indexOf(data.transport)) {
657 this.log.warn('unknown transport: "' + data.transport + '"');
658 req.connection.end();
662 var transport = new transports[data.transport](this, data, req)
663 , handshaken = this.handshaken[data.id];
665 if (transport.disconnected) {
666 // failed during transport setup
667 req.connection.end();
671 if (transport.open) {
672 if (this.closed[data.id] && this.closed[data.id].length) {
673 transport.payload(this.closed[data.id]);
674 this.closed[data.id] = [];
677 this.onOpen(data.id);
678 this.store.publish('open', data.id);
679 this.transports[data.id] = transport;
682 if (!this.connected[data.id]) {
683 this.onConnect(data.id);
684 this.store.publish('connect', data.id);
687 delete handshaken.issued;
688 this.onHandshake(data.id, handshaken);
689 this.store.publish('handshake', data.id, handshaken);
691 // initialize the socket for all namespaces
692 for (var i in this.namespaces) {
693 if (this.namespaces.hasOwnProperty(i)) {
694 var socket = this.namespaces[i].socket(data.id, true);
696 // echo back connect packet and fire connection event
698 this.namespaces[i].handlePacket(data.id, { type: 'connect' });
703 this.store.subscribe('message:' + data.id, function (packet) {
704 self.onClientMessage(data.id, packet);
707 this.store.subscribe('disconnect:' + data.id, function (reason) {
708 self.onClientDisconnect(data.id, reason);
712 if (transport.open) {
713 transport.error('client not handshaken', 'reconnect');
721 * Generates a session id.
726 Manager.prototype.generateId = function () {
727 var rand = new Buffer(15); // multiple of 3 for base64
728 if (!rand.writeInt32BE) {
729 return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
730 + Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
732 this.sequenceNumber = (this.sequenceNumber + 1) | 0;
733 rand.writeInt32BE(this.sequenceNumber, 11);
734 if (crypto.randomBytes) {
735 crypto.randomBytes(12).copy(rand);
737 // not secure for node 0.4
738 [0, 4, 8].forEach(function(i) {
739 rand.writeInt32BE(Math.random() * Math.pow(2, 32) | 0, i);
742 return rand.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
746 * Handles a handshake request.
751 Manager.prototype.handleHandshake = function (data, req, res) {
753 , origin = req.headers.origin
755 'Content-Type': 'text/plain'
758 function writeErr (status, message) {
759 if (data.query.jsonp && jsonpolling_re.test(data.query.jsonp)) {
760 res.writeHead(200, { 'Content-Type': 'application/javascript' });
761 res.end('io.j[' + data.query.jsonp + '](new Error("' + message + '"));');
763 res.writeHead(status, headers);
768 function error (err) {
769 writeErr(500, 'handshake error');
770 self.log.warn('handshake error ' + err);
773 if (!this.verifyOrigin(req)) {
774 writeErr(403, 'handshake bad origin');
778 var handshakeData = this.handshakeData(data);
781 // https://developer.mozilla.org/En/HTTP_Access_Control
782 headers['Access-Control-Allow-Origin'] = origin;
783 headers['Access-Control-Allow-Credentials'] = 'true';
786 this.authorize(handshakeData, function (err, authorized, newData) {
787 if (err) return error(err);
790 var id = self.generateId()
793 , self.enabled('heartbeats') ? self.get('heartbeat timeout') || '' : ''
794 , self.get('close timeout') || ''
795 , self.transports(data).join(',')
798 if (data.query.jsonp && jsonpolling_re.test(data.query.jsonp)) {
799 hs = 'io.j[' + data.query.jsonp + '](' + JSON.stringify(hs) + ');';
800 res.writeHead(200, { 'Content-Type': 'application/javascript' });
802 res.writeHead(200, headers);
807 self.onHandshake(id, newData || handshakeData);
808 self.store.publish('handshake', id, newData || handshakeData);
810 self.log.info('handshake authorized', id);
812 writeErr(403, 'handshake unauthorized');
813 self.log.info('handshake unauthorized');
819 * Gets normalized handshake data
824 Manager.prototype.handshakeData = function (data) {
825 var connection = data.request.connection
829 if (connection.remoteAddress) {
830 connectionAddress = {
831 address: connection.remoteAddress
832 , port: connection.remotePort
834 } else if (connection.socket && connection.socket.remoteAddress) {
835 connectionAddress = {
836 address: connection.socket.remoteAddress
837 , port: connection.socket.remotePort
842 headers: data.headers
843 , address: connectionAddress
844 , time: date.toString()
846 , url: data.request.url
847 , xdomain: !!data.request.headers.origin
848 , secure: data.request.connection.secure
854 * Verifies the origin of a request.
859 Manager.prototype.verifyOrigin = function (request) {
860 var origin = request.headers.origin || request.headers.referer
861 , origins = this.get('origins');
863 if (origin === 'null') origin = '*';
865 if (origins.indexOf('*:*') !== -1) {
871 var parts = url.parse(origin);
872 parts.port = parts.port || 80;
874 ~origins.indexOf(parts.hostname + ':' + parts.port) ||
875 ~origins.indexOf(parts.hostname + ':*') ||
876 ~origins.indexOf('*:' + parts.port);
877 if (!ok) this.log.warn('illegal origin: ' + origin);
880 this.log.warn('error parsing origin');
884 this.log.warn('origin missing from handshake, yet required by config');
890 * Handles an incoming packet.
895 Manager.prototype.handlePacket = function (sessid, packet) {
896 this.of(packet.endpoint || '').handlePacket(sessid, packet);
900 * Performs authentication.
902 * @param Object client request data
906 Manager.prototype.authorize = function (data, fn) {
907 if (this.get('authorization')) {
910 this.get('authorization').call(this, data, function (err, authorized) {
911 self.log.debug('client ' + authorized ? 'authorized' : 'unauthorized');
915 this.log.debug('client authorized');
923 * Retrieves the transports adviced to the user.
928 Manager.prototype.transports = function (data) {
929 var transp = this.get('transports')
932 for (var i = 0, l = transp.length; i < l; i++) {
933 var transport = transp[i];
936 if (!transport.checkClient || transport.checkClient(data)) {
946 * Checks whether a request is a socket.io one.
948 * @return {Object} a client request data object or `false`
952 var regexp = /^\/([^\/]+)\/?([^\/]+)?\/?([^\/]+)?\/?$/
954 Manager.prototype.checkRequest = function (req) {
955 var resource = this.get('resource');
958 if (typeof resource === 'string') {
959 match = req.url.substr(0, resource.length);
960 if (match !== resource) match = null;
962 match = resource.exec(req.url);
963 if (match) match = match[0];
967 var uri = url.parse(req.url.substr(match.length), true)
968 , path = uri.pathname || ''
969 , pieces = path.match(regexp);
971 // client request data
973 query: uri.query || {}
974 , headers: req.headers
980 data.protocol = Number(pieces[1]);
981 data.transport = pieces[2];
983 data.static = !!this.static.has(path);
993 * Declares a socket namespace
998 Manager.prototype.of = function (nsp) {
999 if (this.namespaces[nsp]) {
1000 return this.namespaces[nsp];
1003 return this.namespaces[nsp] = new SocketNamespace(this, nsp);
1007 * Perform garbage collection on long living objects and properties that cannot
1008 * be removed automatically.
1013 Manager.prototype.garbageCollection = function () {
1014 // clean up unused handshakes
1015 var ids = Object.keys(this.handshaken)
1021 handshake = this.handshaken[ids[i]];
1023 if ('issued' in handshake && (now - handshake.issued) >= 3E4) {
1024 this.onDisconnect(ids[i]);