manager.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. /*!
  2. * socket.io-node
  3. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module dependencies.
  8. */
  9. var fs = require('fs')
  10. , url = require('url')
  11. , tty = require('tty')
  12. , crypto = require('crypto')
  13. , util = require('./util')
  14. , store = require('./store')
  15. , client = require('socket.io-client')
  16. , transports = require('./transports')
  17. , Logger = require('./logger')
  18. , Socket = require('./socket')
  19. , MemoryStore = require('./stores/memory')
  20. , SocketNamespace = require('./namespace')
  21. , Static = require('./static')
  22. , EventEmitter = process.EventEmitter;
  23. /**
  24. * Export the constructor.
  25. */
  26. exports = module.exports = Manager;
  27. /**
  28. * Default transports.
  29. */
  30. var defaultTransports = exports.defaultTransports = [
  31. 'websocket'
  32. , 'htmlfile'
  33. , 'xhr-polling'
  34. , 'jsonp-polling'
  35. ];
  36. /**
  37. * Inherited defaults.
  38. */
  39. var parent = module.parent.exports
  40. , protocol = parent.protocol
  41. , jsonpolling_re = /^\d+$/;
  42. /**
  43. * Manager constructor.
  44. *
  45. * @param {HTTPServer} server
  46. * @param {Object} options, optional
  47. * @api public
  48. */
  49. function Manager (server, options) {
  50. this.server = server;
  51. this.namespaces = {};
  52. this.sockets = this.of('');
  53. this.settings = {
  54. origins: '*:*'
  55. , log: true
  56. , store: new MemoryStore
  57. , logger: new Logger
  58. , static: new Static(this)
  59. , heartbeats: true
  60. , resource: '/socket.io'
  61. , transports: defaultTransports
  62. , authorization: false
  63. , blacklist: ['disconnect']
  64. , 'log level': 3
  65. , 'log colors': tty.isatty(process.stdout.fd)
  66. , 'close timeout': 60
  67. , 'heartbeat interval': 25
  68. , 'heartbeat timeout': 60
  69. , 'polling duration': 20
  70. , 'flash policy server': true
  71. , 'flash policy port': 10843
  72. , 'destroy upgrade': true
  73. , 'destroy buffer size': 10E7
  74. , 'browser client': true
  75. , 'browser client cache': true
  76. , 'browser client minification': false
  77. , 'browser client etag': false
  78. , 'browser client expires': 315360000
  79. , 'browser client gzip': false
  80. , 'browser client handler': false
  81. , 'client store expiration': 15
  82. , 'match origin protocol': false
  83. };
  84. for (var i in options) {
  85. if (options.hasOwnProperty(i)) {
  86. this.settings[i] = options[i];
  87. }
  88. }
  89. var self = this;
  90. // default error handler
  91. server.on('error', function(err) {
  92. self.log.warn('error raised: ' + err);
  93. });
  94. this.initStore();
  95. this.on('set:store', function() {
  96. self.initStore();
  97. });
  98. // reset listeners
  99. this.oldListeners = server.listeners('request').splice(0);
  100. server.removeAllListeners('request');
  101. server.on('request', function (req, res) {
  102. self.handleRequest(req, res);
  103. });
  104. server.on('upgrade', function (req, socket, head) {
  105. self.handleUpgrade(req, socket, head);
  106. });
  107. server.on('close', function () {
  108. clearInterval(self.gc);
  109. });
  110. server.once('listening', function () {
  111. self.gc = setInterval(self.garbageCollection.bind(self), 10000);
  112. });
  113. for (var i in transports) {
  114. if (transports.hasOwnProperty(i)) {
  115. if (transports[i].init) {
  116. transports[i].init(this);
  117. }
  118. }
  119. }
  120. // forward-compatibility with 1.0
  121. var self = this;
  122. this.sockets.on('connection', function (conn) {
  123. self.emit('connection', conn);
  124. });
  125. this.sequenceNumber = Date.now() | 0;
  126. this.log.info('socket.io started');
  127. };
  128. Manager.prototype.__proto__ = EventEmitter.prototype
  129. /**
  130. * Store accessor shortcut.
  131. *
  132. * @api public
  133. */
  134. Manager.prototype.__defineGetter__('store', function () {
  135. var store = this.get('store');
  136. store.manager = this;
  137. return store;
  138. });
  139. /**
  140. * Logger accessor.
  141. *
  142. * @api public
  143. */
  144. Manager.prototype.__defineGetter__('log', function () {
  145. var logger = this.get('logger');
  146. logger.level = this.get('log level') || -1;
  147. logger.colors = this.get('log colors');
  148. logger.enabled = this.enabled('log');
  149. return logger;
  150. });
  151. /**
  152. * Static accessor.
  153. *
  154. * @api public
  155. */
  156. Manager.prototype.__defineGetter__('static', function () {
  157. return this.get('static');
  158. });
  159. /**
  160. * Get settings.
  161. *
  162. * @api public
  163. */
  164. Manager.prototype.get = function (key) {
  165. return this.settings[key];
  166. };
  167. /**
  168. * Set settings
  169. *
  170. * @api public
  171. */
  172. Manager.prototype.set = function (key, value) {
  173. if (arguments.length == 1) return this.get(key);
  174. this.settings[key] = value;
  175. this.emit('set:' + key, this.settings[key], key);
  176. return this;
  177. };
  178. /**
  179. * Enable a setting
  180. *
  181. * @api public
  182. */
  183. Manager.prototype.enable = function (key) {
  184. this.settings[key] = true;
  185. this.emit('set:' + key, this.settings[key], key);
  186. return this;
  187. };
  188. /**
  189. * Disable a setting
  190. *
  191. * @api public
  192. */
  193. Manager.prototype.disable = function (key) {
  194. this.settings[key] = false;
  195. this.emit('set:' + key, this.settings[key], key);
  196. return this;
  197. };
  198. /**
  199. * Checks if a setting is enabled
  200. *
  201. * @api public
  202. */
  203. Manager.prototype.enabled = function (key) {
  204. return !!this.settings[key];
  205. };
  206. /**
  207. * Checks if a setting is disabled
  208. *
  209. * @api public
  210. */
  211. Manager.prototype.disabled = function (key) {
  212. return !this.settings[key];
  213. };
  214. /**
  215. * Configure callbacks.
  216. *
  217. * @api public
  218. */
  219. Manager.prototype.configure = function (env, fn) {
  220. if ('function' == typeof env) {
  221. env.call(this);
  222. } else if (env == (process.env.NODE_ENV || 'development')) {
  223. fn.call(this);
  224. }
  225. return this;
  226. };
  227. /**
  228. * Initializes everything related to the message dispatcher.
  229. *
  230. * @api private
  231. */
  232. Manager.prototype.initStore = function () {
  233. this.handshaken = {};
  234. this.connected = {};
  235. this.open = {};
  236. this.closed = {};
  237. this.rooms = {};
  238. this.roomClients = {};
  239. var self = this;
  240. this.store.subscribe('handshake', function (id, data) {
  241. self.onHandshake(id, data);
  242. });
  243. this.store.subscribe('connect', function (id) {
  244. self.onConnect(id);
  245. });
  246. this.store.subscribe('open', function (id) {
  247. self.onOpen(id);
  248. });
  249. this.store.subscribe('join', function (id, room) {
  250. self.onJoin(id, room);
  251. });
  252. this.store.subscribe('leave', function (id, room) {
  253. self.onLeave(id, room);
  254. });
  255. this.store.subscribe('close', function (id) {
  256. self.onClose(id);
  257. });
  258. this.store.subscribe('dispatch', function (room, packet, volatile, exceptions) {
  259. self.onDispatch(room, packet, volatile, exceptions);
  260. });
  261. this.store.subscribe('disconnect', function (id) {
  262. self.onDisconnect(id);
  263. });
  264. };
  265. /**
  266. * Called when a client handshakes.
  267. *
  268. * @param text
  269. */
  270. Manager.prototype.onHandshake = function (id, data) {
  271. this.handshaken[id] = data;
  272. };
  273. /**
  274. * Called when a client connects (ie: transport first opens)
  275. *
  276. * @api private
  277. */
  278. Manager.prototype.onConnect = function (id) {
  279. this.connected[id] = true;
  280. };
  281. /**
  282. * Called when a client opens a request in a different node.
  283. *
  284. * @api private
  285. */
  286. Manager.prototype.onOpen = function (id) {
  287. this.open[id] = true;
  288. if (this.closed[id]) {
  289. var self = this;
  290. this.store.unsubscribe('dispatch:' + id, function () {
  291. var transport = self.transports[id];
  292. if (self.closed[id] && self.closed[id].length && transport) {
  293. // if we have buffered messages that accumulate between calling
  294. // onOpen an this async callback, send them if the transport is
  295. // still open, otherwise leave them buffered
  296. if (transport.open) {
  297. transport.payload(self.closed[id]);
  298. self.closed[id] = [];
  299. }
  300. }
  301. });
  302. }
  303. // clear the current transport
  304. if (this.transports[id]) {
  305. this.transports[id].discard();
  306. this.transports[id] = null;
  307. }
  308. };
  309. /**
  310. * Called when a message is sent to a namespace and/or room.
  311. *
  312. * @api private
  313. */
  314. Manager.prototype.onDispatch = function (room, packet, volatile, exceptions) {
  315. if (this.rooms[room]) {
  316. for (var i = 0, l = this.rooms[room].length; i < l; i++) {
  317. var id = this.rooms[room][i];
  318. if (!~exceptions.indexOf(id)) {
  319. if (this.transports[id] && this.transports[id].open) {
  320. this.transports[id].onDispatch(packet, volatile);
  321. } else if (!volatile) {
  322. this.onClientDispatch(id, packet);
  323. }
  324. }
  325. }
  326. }
  327. };
  328. /**
  329. * Called when a client joins a nsp / room.
  330. *
  331. * @api private
  332. */
  333. Manager.prototype.onJoin = function (id, name) {
  334. if (!this.roomClients[id]) {
  335. this.roomClients[id] = {};
  336. }
  337. if (!this.rooms[name]) {
  338. this.rooms[name] = [];
  339. }
  340. if (!~this.rooms[name].indexOf(id)) {
  341. this.rooms[name].push(id);
  342. this.roomClients[id][name] = true;
  343. }
  344. };
  345. /**
  346. * Called when a client leaves a nsp / room.
  347. *
  348. * @param private
  349. */
  350. Manager.prototype.onLeave = function (id, room) {
  351. if (this.rooms[room]) {
  352. var index = this.rooms[room].indexOf(id);
  353. if (index >= 0) {
  354. this.rooms[room].splice(index, 1);
  355. }
  356. if (!this.rooms[room].length) {
  357. delete this.rooms[room];
  358. }
  359. if (this.roomClients[id]) {
  360. delete this.roomClients[id][room];
  361. }
  362. }
  363. };
  364. /**
  365. * Called when a client closes a request in different node.
  366. *
  367. * @api private
  368. */
  369. Manager.prototype.onClose = function (id) {
  370. if (this.open[id]) {
  371. delete this.open[id];
  372. }
  373. this.closed[id] = [];
  374. var self = this;
  375. this.store.subscribe('dispatch:' + id, function (packet, volatile) {
  376. if (!volatile) {
  377. self.onClientDispatch(id, packet);
  378. }
  379. });
  380. };
  381. /**
  382. * Dispatches a message for a closed client.
  383. *
  384. * @api private
  385. */
  386. Manager.prototype.onClientDispatch = function (id, packet) {
  387. if (this.closed[id]) {
  388. this.closed[id].push(packet);
  389. }
  390. };
  391. /**
  392. * Receives a message for a client.
  393. *
  394. * @api private
  395. */
  396. Manager.prototype.onClientMessage = function (id, packet) {
  397. if (this.namespaces[packet.endpoint]) {
  398. this.namespaces[packet.endpoint].handlePacket(id, packet);
  399. }
  400. };
  401. /**
  402. * Fired when a client disconnects (not triggered).
  403. *
  404. * @api private
  405. */
  406. Manager.prototype.onClientDisconnect = function (id, reason) {
  407. for (var name in this.namespaces) {
  408. if (this.namespaces.hasOwnProperty(name)) {
  409. this.namespaces[name].handleDisconnect(id, reason, typeof this.roomClients[id] !== 'undefined' &&
  410. typeof this.roomClients[id][name] !== 'undefined');
  411. }
  412. }
  413. this.onDisconnect(id);
  414. };
  415. /**
  416. * Called when a client disconnects.
  417. *
  418. * @param text
  419. */
  420. Manager.prototype.onDisconnect = function (id, local) {
  421. delete this.handshaken[id];
  422. if (this.open[id]) {
  423. delete this.open[id];
  424. }
  425. if (this.connected[id]) {
  426. delete this.connected[id];
  427. }
  428. if (this.transports[id]) {
  429. this.transports[id].discard();
  430. delete this.transports[id];
  431. }
  432. if (this.closed[id]) {
  433. delete this.closed[id];
  434. }
  435. if (this.roomClients[id]) {
  436. for (var room in this.roomClients[id]) {
  437. if (this.roomClients[id].hasOwnProperty(room)) {
  438. this.onLeave(id, room);
  439. }
  440. }
  441. delete this.roomClients[id]
  442. }
  443. this.store.destroyClient(id, this.get('client store expiration'));
  444. this.store.unsubscribe('dispatch:' + id);
  445. if (local) {
  446. this.store.unsubscribe('message:' + id);
  447. this.store.unsubscribe('disconnect:' + id);
  448. }
  449. };
  450. /**
  451. * Handles an HTTP request.
  452. *
  453. * @api private
  454. */
  455. Manager.prototype.handleRequest = function (req, res) {
  456. var data = this.checkRequest(req);
  457. if (!data) {
  458. for (var i = 0, l = this.oldListeners.length; i < l; i++) {
  459. this.oldListeners[i].call(this.server, req, res);
  460. }
  461. return;
  462. }
  463. if (data.static || !data.transport && !data.protocol) {
  464. if (data.static && this.enabled('browser client')) {
  465. this.static.write(data.path, req, res);
  466. } else {
  467. res.writeHead(200);
  468. res.end('Welcome to socket.io.');
  469. this.log.info('unhandled socket.io url');
  470. }
  471. return;
  472. }
  473. if (data.protocol != protocol) {
  474. res.writeHead(500);
  475. res.end('Protocol version not supported.');
  476. this.log.info('client protocol version unsupported');
  477. } else {
  478. if (data.id) {
  479. this.handleHTTPRequest(data, req, res);
  480. } else {
  481. this.handleHandshake(data, req, res);
  482. }
  483. }
  484. };
  485. /**
  486. * Handles an HTTP Upgrade.
  487. *
  488. * @api private
  489. */
  490. Manager.prototype.handleUpgrade = function (req, socket, head) {
  491. var data = this.checkRequest(req)
  492. , self = this;
  493. if (!data) {
  494. if (this.enabled('destroy upgrade')) {
  495. socket.end();
  496. this.log.debug('destroying non-socket.io upgrade');
  497. }
  498. return;
  499. }
  500. req.head = head;
  501. this.handleClient(data, req);
  502. };
  503. /**
  504. * Handles a normal handshaken HTTP request (eg: long-polling)
  505. *
  506. * @api private
  507. */
  508. Manager.prototype.handleHTTPRequest = function (data, req, res) {
  509. req.res = res;
  510. this.handleClient(data, req);
  511. };
  512. /**
  513. * Intantiantes a new client.
  514. *
  515. * @api private
  516. */
  517. Manager.prototype.handleClient = function (data, req) {
  518. var socket = req.socket
  519. , store = this.store
  520. , self = this;
  521. // handle sync disconnect xhrs
  522. if (undefined != data.query.disconnect) {
  523. if (this.transports[data.id] && this.transports[data.id].open) {
  524. this.transports[data.id].onForcedDisconnect();
  525. } else {
  526. this.store.publish('disconnect-force:' + data.id);
  527. }
  528. req.res.writeHead(200);
  529. req.res.end();
  530. return;
  531. }
  532. if (!~this.get('transports').indexOf(data.transport)) {
  533. this.log.warn('unknown transport: "' + data.transport + '"');
  534. req.connection.end();
  535. return;
  536. }
  537. var transport = new transports[data.transport](this, data, req)
  538. , handshaken = this.handshaken[data.id];
  539. if (transport.disconnected) {
  540. // failed during transport setup
  541. req.connection.end();
  542. return;
  543. }
  544. if (handshaken) {
  545. if (transport.open) {
  546. if (this.closed[data.id] && this.closed[data.id].length) {
  547. transport.payload(this.closed[data.id]);
  548. this.closed[data.id] = [];
  549. }
  550. this.onOpen(data.id);
  551. this.store.publish('open', data.id);
  552. this.transports[data.id] = transport;
  553. }
  554. if (!this.connected[data.id]) {
  555. this.onConnect(data.id);
  556. this.store.publish('connect', data.id);
  557. // flag as used
  558. delete handshaken.issued;
  559. this.onHandshake(data.id, handshaken);
  560. this.store.publish('handshake', data.id, handshaken);
  561. // initialize the socket for all namespaces
  562. for (var i in this.namespaces) {
  563. if (this.namespaces.hasOwnProperty(i)) {
  564. var socket = this.namespaces[i].socket(data.id, true);
  565. // echo back connect packet and fire connection event
  566. if (i === '') {
  567. this.namespaces[i].handlePacket(data.id, { type: 'connect' });
  568. }
  569. }
  570. }
  571. this.store.subscribe('message:' + data.id, function (packet) {
  572. self.onClientMessage(data.id, packet);
  573. });
  574. this.store.subscribe('disconnect:' + data.id, function (reason) {
  575. self.onClientDisconnect(data.id, reason);
  576. });
  577. }
  578. } else {
  579. if (transport.open) {
  580. transport.error('client not handshaken', 'reconnect');
  581. }
  582. transport.discard();
  583. }
  584. };
  585. /**
  586. * Generates a session id.
  587. *
  588. * @api private
  589. */
  590. Manager.prototype.generateId = function () {
  591. var rand = new Buffer(15); // multiple of 3 for base64
  592. if (!rand.writeInt32BE) {
  593. return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
  594. + Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
  595. }
  596. this.sequenceNumber = (this.sequenceNumber + 1) | 0;
  597. rand.writeInt32BE(this.sequenceNumber, 11);
  598. if (crypto.randomBytes) {
  599. crypto.randomBytes(12).copy(rand);
  600. } else {
  601. // not secure for node 0.4
  602. [0, 4, 8].forEach(function(i) {
  603. rand.writeInt32BE(Math.random() * Math.pow(2, 32) | 0, i);
  604. });
  605. }
  606. return rand.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
  607. };
  608. /**
  609. * Handles a handshake request.
  610. *
  611. * @api private
  612. */
  613. Manager.prototype.handleHandshake = function (data, req, res) {
  614. var self = this
  615. , origin = req.headers.origin
  616. , headers = {
  617. 'Content-Type': 'text/plain'
  618. };
  619. function writeErr (status, message) {
  620. if (data.query.jsonp && jsonpolling_re.test(data.query.jsonp)) {
  621. res.writeHead(200, { 'Content-Type': 'application/javascript' });
  622. res.end('io.j[' + data.query.jsonp + '](new Error("' + message + '"));');
  623. } else {
  624. res.writeHead(status, headers);
  625. res.end(message);
  626. }
  627. };
  628. function error (err) {
  629. writeErr(500, 'handshake error');
  630. self.log.warn('handshake error ' + err);
  631. };
  632. if (!this.verifyOrigin(req)) {
  633. writeErr(403, 'handshake bad origin');
  634. return;
  635. }
  636. var handshakeData = this.handshakeData(data);
  637. if (origin) {
  638. // https://developer.mozilla.org/En/HTTP_Access_Control
  639. headers['Access-Control-Allow-Origin'] = origin;
  640. headers['Access-Control-Allow-Credentials'] = 'true';
  641. }
  642. this.authorize(handshakeData, function (err, authorized, newData) {
  643. if (err) return error(err);
  644. if (authorized) {
  645. var id = self.generateId()
  646. , hs = [
  647. id
  648. , self.enabled('heartbeats') ? self.get('heartbeat timeout') || '' : ''
  649. , self.get('close timeout') || ''
  650. , self.transports(data).join(',')
  651. ].join(':');
  652. if (data.query.jsonp && jsonpolling_re.test(data.query.jsonp)) {
  653. hs = 'io.j[' + data.query.jsonp + '](' + JSON.stringify(hs) + ');';
  654. res.writeHead(200, { 'Content-Type': 'application/javascript' });
  655. } else {
  656. res.writeHead(200, headers);
  657. }
  658. res.end(hs);
  659. self.onHandshake(id, newData || handshakeData);
  660. self.store.publish('handshake', id, newData || handshakeData);
  661. self.log.info('handshake authorized', id);
  662. } else {
  663. writeErr(403, 'handshake unauthorized');
  664. self.log.info('handshake unauthorized');
  665. }
  666. })
  667. };
  668. /**
  669. * Gets normalized handshake data
  670. *
  671. * @api private
  672. */
  673. Manager.prototype.handshakeData = function (data) {
  674. var connection = data.request.connection
  675. , connectionAddress
  676. , date = new Date;
  677. if (connection.remoteAddress) {
  678. connectionAddress = {
  679. address: connection.remoteAddress
  680. , port: connection.remotePort
  681. };
  682. } else if (connection.socket && connection.socket.remoteAddress) {
  683. connectionAddress = {
  684. address: connection.socket.remoteAddress
  685. , port: connection.socket.remotePort
  686. };
  687. }
  688. return {
  689. headers: data.headers
  690. , address: connectionAddress
  691. , time: date.toString()
  692. , query: data.query
  693. , url: data.request.url
  694. , xdomain: !!data.request.headers.origin
  695. , secure: data.request.connection.secure
  696. , issued: +date
  697. };
  698. };
  699. /**
  700. * Verifies the origin of a request.
  701. *
  702. * @api private
  703. */
  704. Manager.prototype.verifyOrigin = function (request) {
  705. var origin = request.headers.origin || request.headers.referer
  706. , origins = this.get('origins');
  707. if (origin === 'null') origin = '*';
  708. if (origins.indexOf('*:*') !== -1) {
  709. return true;
  710. }
  711. if (origin) {
  712. try {
  713. var parts = url.parse(origin);
  714. parts.port = parts.port || 80;
  715. var ok =
  716. ~origins.indexOf(parts.hostname + ':' + parts.port) ||
  717. ~origins.indexOf(parts.hostname + ':*') ||
  718. ~origins.indexOf('*:' + parts.port);
  719. if (!ok) this.log.warn('illegal origin: ' + origin);
  720. return ok;
  721. } catch (ex) {
  722. this.log.warn('error parsing origin');
  723. }
  724. }
  725. else {
  726. this.log.warn('origin missing from handshake, yet required by config');
  727. }
  728. return false;
  729. };
  730. /**
  731. * Handles an incoming packet.
  732. *
  733. * @api private
  734. */
  735. Manager.prototype.handlePacket = function (sessid, packet) {
  736. this.of(packet.endpoint || '').handlePacket(sessid, packet);
  737. };
  738. /**
  739. * Performs authentication.
  740. *
  741. * @param Object client request data
  742. * @api private
  743. */
  744. Manager.prototype.authorize = function (data, fn) {
  745. if (this.get('authorization')) {
  746. var self = this;
  747. this.get('authorization').call(this, data, function (err, authorized) {
  748. self.log.debug('client ' + authorized ? 'authorized' : 'unauthorized');
  749. fn(err, authorized);
  750. });
  751. } else {
  752. this.log.debug('client authorized');
  753. fn(null, true);
  754. }
  755. return this;
  756. };
  757. /**
  758. * Retrieves the transports adviced to the user.
  759. *
  760. * @api private
  761. */
  762. Manager.prototype.transports = function (data) {
  763. var transp = this.get('transports')
  764. , ret = [];
  765. for (var i = 0, l = transp.length; i < l; i++) {
  766. var transport = transp[i];
  767. if (transport) {
  768. if (!transport.checkClient || transport.checkClient(data)) {
  769. ret.push(transport);
  770. }
  771. }
  772. }
  773. return ret;
  774. };
  775. /**
  776. * Checks whether a request is a socket.io one.
  777. *
  778. * @return {Object} a client request data object or `false`
  779. * @api private
  780. */
  781. var regexp = /^\/([^\/]+)\/?([^\/]+)?\/?([^\/]+)?\/?$/
  782. Manager.prototype.checkRequest = function (req) {
  783. var resource = this.get('resource');
  784. var match;
  785. if (typeof resource === 'string') {
  786. match = req.url.substr(0, resource.length);
  787. if (match !== resource) match = null;
  788. } else {
  789. match = resource.exec(req.url);
  790. if (match) match = match[0];
  791. }
  792. if (match) {
  793. var uri = url.parse(req.url.substr(match.length), true)
  794. , path = uri.pathname || ''
  795. , pieces = path.match(regexp);
  796. // client request data
  797. var data = {
  798. query: uri.query || {}
  799. , headers: req.headers
  800. , request: req
  801. , path: path
  802. };
  803. if (pieces) {
  804. data.protocol = Number(pieces[1]);
  805. data.transport = pieces[2];
  806. data.id = pieces[3];
  807. data.static = !!this.static.has(path);
  808. };
  809. return data;
  810. }
  811. return false;
  812. };
  813. /**
  814. * Declares a socket namespace
  815. *
  816. * @api public
  817. */
  818. Manager.prototype.of = function (nsp) {
  819. if (this.namespaces[nsp]) {
  820. return this.namespaces[nsp];
  821. }
  822. return this.namespaces[nsp] = new SocketNamespace(this, nsp);
  823. };
  824. /**
  825. * Perform garbage collection on long living objects and properties that cannot
  826. * be removed automatically.
  827. *
  828. * @api private
  829. */
  830. Manager.prototype.garbageCollection = function () {
  831. // clean up unused handshakes
  832. var ids = Object.keys(this.handshaken)
  833. , i = ids.length
  834. , now = Date.now()
  835. , handshake;
  836. while (i--) {
  837. handshake = this.handshaken[ids[i]];
  838. if ('issued' in handshake && (now - handshake.issued) >= 3E4) {
  839. this.onDisconnect(ids[i]);
  840. }
  841. }
  842. };