manager.js 22 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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. req.head = null;
  503. };
  504. /**
  505. * Handles a normal handshaken HTTP request (eg: long-polling)
  506. *
  507. * @api private
  508. */
  509. Manager.prototype.handleHTTPRequest = function (data, req, res) {
  510. req.res = res;
  511. this.handleClient(data, req);
  512. };
  513. /**
  514. * Intantiantes a new client.
  515. *
  516. * @api private
  517. */
  518. Manager.prototype.handleClient = function (data, req) {
  519. var socket = req.socket
  520. , store = this.store
  521. , self = this;
  522. // handle sync disconnect xhrs
  523. if (undefined != data.query.disconnect) {
  524. if (this.transports[data.id] && this.transports[data.id].open) {
  525. this.transports[data.id].onForcedDisconnect();
  526. } else {
  527. this.store.publish('disconnect-force:' + data.id);
  528. }
  529. req.res.writeHead(200);
  530. req.res.end();
  531. return;
  532. }
  533. if (!~this.get('transports').indexOf(data.transport)) {
  534. this.log.warn('unknown transport: "' + data.transport + '"');
  535. req.connection.end();
  536. return;
  537. }
  538. var transport = new transports[data.transport](this, data, req)
  539. , handshaken = this.handshaken[data.id];
  540. if (transport.disconnected) {
  541. // failed during transport setup
  542. req.connection.end();
  543. return;
  544. }
  545. if (handshaken) {
  546. if (transport.open) {
  547. if (this.closed[data.id] && this.closed[data.id].length) {
  548. transport.payload(this.closed[data.id]);
  549. this.closed[data.id] = [];
  550. }
  551. this.onOpen(data.id);
  552. this.store.publish('open', data.id);
  553. this.transports[data.id] = transport;
  554. }
  555. if (!this.connected[data.id]) {
  556. this.onConnect(data.id);
  557. this.store.publish('connect', data.id);
  558. // flag as used
  559. delete handshaken.issued;
  560. this.onHandshake(data.id, handshaken);
  561. this.store.publish('handshake', data.id, handshaken);
  562. // initialize the socket for all namespaces
  563. for (var i in this.namespaces) {
  564. if (this.namespaces.hasOwnProperty(i)) {
  565. var socket = this.namespaces[i].socket(data.id, true);
  566. // echo back connect packet and fire connection event
  567. if (i === '') {
  568. this.namespaces[i].handlePacket(data.id, { type: 'connect' });
  569. }
  570. }
  571. }
  572. this.store.subscribe('message:' + data.id, function (packet) {
  573. self.onClientMessage(data.id, packet);
  574. });
  575. this.store.subscribe('disconnect:' + data.id, function (reason) {
  576. self.onClientDisconnect(data.id, reason);
  577. });
  578. }
  579. } else {
  580. if (transport.open) {
  581. transport.error('client not handshaken', 'reconnect');
  582. }
  583. transport.discard();
  584. }
  585. };
  586. /**
  587. * Generates a session id.
  588. *
  589. * @api private
  590. */
  591. Manager.prototype.generateId = function () {
  592. var rand = new Buffer(15); // multiple of 3 for base64
  593. if (!rand.writeInt32BE) {
  594. return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
  595. + Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
  596. }
  597. this.sequenceNumber = (this.sequenceNumber + 1) | 0;
  598. rand.writeInt32BE(this.sequenceNumber, 11);
  599. if (crypto.randomBytes) {
  600. crypto.randomBytes(12).copy(rand);
  601. } else {
  602. // not secure for node 0.4
  603. [0, 4, 8].forEach(function(i) {
  604. rand.writeInt32BE(Math.random() * Math.pow(2, 32) | 0, i);
  605. });
  606. }
  607. return rand.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
  608. };
  609. /**
  610. * Handles a handshake request.
  611. *
  612. * @api private
  613. */
  614. Manager.prototype.handleHandshake = function (data, req, res) {
  615. var self = this
  616. , origin = req.headers.origin
  617. , headers = {
  618. 'Content-Type': 'text/plain'
  619. };
  620. function writeErr (status, message) {
  621. if (data.query.jsonp && jsonpolling_re.test(data.query.jsonp)) {
  622. res.writeHead(200, { 'Content-Type': 'application/javascript' });
  623. res.end('io.j[' + data.query.jsonp + '](new Error("' + message + '"));');
  624. } else {
  625. res.writeHead(status, headers);
  626. res.end(message);
  627. }
  628. };
  629. function error (err) {
  630. writeErr(500, 'handshake error');
  631. self.log.warn('handshake error ' + err);
  632. };
  633. if (!this.verifyOrigin(req)) {
  634. writeErr(403, 'handshake bad origin');
  635. return;
  636. }
  637. var handshakeData = this.handshakeData(data);
  638. if (origin) {
  639. // https://developer.mozilla.org/En/HTTP_Access_Control
  640. headers['Access-Control-Allow-Origin'] = origin;
  641. headers['Access-Control-Allow-Credentials'] = 'true';
  642. }
  643. this.authorize(handshakeData, function (err, authorized, newData) {
  644. if (err) return error(err);
  645. if (authorized) {
  646. var id = self.generateId()
  647. , hs = [
  648. id
  649. , self.enabled('heartbeats') ? self.get('heartbeat timeout') || '' : ''
  650. , self.get('close timeout') || ''
  651. , self.transports(data).join(',')
  652. ].join(':');
  653. if (data.query.jsonp && jsonpolling_re.test(data.query.jsonp)) {
  654. hs = 'io.j[' + data.query.jsonp + '](' + JSON.stringify(hs) + ');';
  655. res.writeHead(200, { 'Content-Type': 'application/javascript' });
  656. } else {
  657. res.writeHead(200, headers);
  658. }
  659. res.end(hs);
  660. self.onHandshake(id, newData || handshakeData);
  661. self.store.publish('handshake', id, newData || handshakeData);
  662. self.log.info('handshake authorized', id);
  663. } else {
  664. writeErr(403, 'handshake unauthorized');
  665. self.log.info('handshake unauthorized');
  666. }
  667. })
  668. };
  669. /**
  670. * Gets normalized handshake data
  671. *
  672. * @api private
  673. */
  674. Manager.prototype.handshakeData = function (data) {
  675. var connection = data.request.connection
  676. , connectionAddress
  677. , date = new Date;
  678. if (connection.remoteAddress) {
  679. connectionAddress = {
  680. address: connection.remoteAddress
  681. , port: connection.remotePort
  682. };
  683. } else if (connection.socket && connection.socket.remoteAddress) {
  684. connectionAddress = {
  685. address: connection.socket.remoteAddress
  686. , port: connection.socket.remotePort
  687. };
  688. }
  689. return {
  690. headers: data.headers
  691. , address: connectionAddress
  692. , time: date.toString()
  693. , query: data.query
  694. , url: data.request.url
  695. , xdomain: !!data.request.headers.origin
  696. , secure: data.request.connection.secure
  697. , issued: +date
  698. };
  699. };
  700. /**
  701. * Verifies the origin of a request.
  702. *
  703. * @api private
  704. */
  705. Manager.prototype.verifyOrigin = function (request) {
  706. var origin = request.headers.origin || request.headers.referer
  707. , origins = this.get('origins');
  708. if (origin === 'null') origin = '*';
  709. if (origins.indexOf('*:*') !== -1) {
  710. return true;
  711. }
  712. if (origin) {
  713. try {
  714. var parts = url.parse(origin);
  715. parts.port = parts.port || 80;
  716. var ok =
  717. ~origins.indexOf(parts.hostname + ':' + parts.port) ||
  718. ~origins.indexOf(parts.hostname + ':*') ||
  719. ~origins.indexOf('*:' + parts.port);
  720. if (!ok) this.log.warn('illegal origin: ' + origin);
  721. return ok;
  722. } catch (ex) {
  723. this.log.warn('error parsing origin');
  724. }
  725. }
  726. else {
  727. this.log.warn('origin missing from handshake, yet required by config');
  728. }
  729. return false;
  730. };
  731. /**
  732. * Handles an incoming packet.
  733. *
  734. * @api private
  735. */
  736. Manager.prototype.handlePacket = function (sessid, packet) {
  737. this.of(packet.endpoint || '').handlePacket(sessid, packet);
  738. };
  739. /**
  740. * Performs authentication.
  741. *
  742. * @param Object client request data
  743. * @api private
  744. */
  745. Manager.prototype.authorize = function (data, fn) {
  746. if (this.get('authorization')) {
  747. var self = this;
  748. this.get('authorization').call(this, data, function (err, authorized) {
  749. self.log.debug('client ' + authorized ? 'authorized' : 'unauthorized');
  750. fn(err, authorized);
  751. });
  752. } else {
  753. this.log.debug('client authorized');
  754. fn(null, true);
  755. }
  756. return this;
  757. };
  758. /**
  759. * Retrieves the transports adviced to the user.
  760. *
  761. * @api private
  762. */
  763. Manager.prototype.transports = function (data) {
  764. var transp = this.get('transports')
  765. , ret = [];
  766. for (var i = 0, l = transp.length; i < l; i++) {
  767. var transport = transp[i];
  768. if (transport) {
  769. if (!transport.checkClient || transport.checkClient(data)) {
  770. ret.push(transport);
  771. }
  772. }
  773. }
  774. return ret;
  775. };
  776. /**
  777. * Checks whether a request is a socket.io one.
  778. *
  779. * @return {Object} a client request data object or `false`
  780. * @api private
  781. */
  782. var regexp = /^\/([^\/]+)\/?([^\/]+)?\/?([^\/]+)?\/?$/
  783. Manager.prototype.checkRequest = function (req) {
  784. var resource = this.get('resource');
  785. var match;
  786. if (typeof resource === 'string') {
  787. match = req.url.substr(0, resource.length);
  788. if (match !== resource) match = null;
  789. } else {
  790. match = resource.exec(req.url);
  791. if (match) match = match[0];
  792. }
  793. if (match) {
  794. var uri = url.parse(req.url.substr(match.length), true)
  795. , path = uri.pathname || ''
  796. , pieces = path.match(regexp);
  797. // client request data
  798. var data = {
  799. query: uri.query || {}
  800. , headers: req.headers
  801. , request: req
  802. , path: path
  803. };
  804. if (pieces) {
  805. data.protocol = Number(pieces[1]);
  806. data.transport = pieces[2];
  807. data.id = pieces[3];
  808. data.static = !!this.static.has(path);
  809. };
  810. return data;
  811. }
  812. return false;
  813. };
  814. /**
  815. * Declares a socket namespace
  816. *
  817. * @api public
  818. */
  819. Manager.prototype.of = function (nsp) {
  820. if (this.namespaces[nsp]) {
  821. return this.namespaces[nsp];
  822. }
  823. return this.namespaces[nsp] = new SocketNamespace(this, nsp);
  824. };
  825. /**
  826. * Perform garbage collection on long living objects and properties that cannot
  827. * be removed automatically.
  828. *
  829. * @api private
  830. */
  831. Manager.prototype.garbageCollection = function () {
  832. // clean up unused handshakes
  833. var ids = Object.keys(this.handshaken)
  834. , i = ids.length
  835. , now = Date.now()
  836. , handshake;
  837. while (i--) {
  838. handshake = this.handshaken[ids[i]];
  839. if ('issued' in handshake && (now - handshake.issued) >= 3E4) {
  840. this.onDisconnect(ids[i]);
  841. }
  842. }
  843. };