manager.js 22 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. /*!
  2. * socket.io-node
  3. * Copyright(c) 2011 LearnBoost <[email protected]>
  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. };