server.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. var util = require('./util');
  2. var bodyParser = require('body-parser');
  3. var WebSocketServer = require('ws').Server;
  4. var url = require('url');
  5. var app = exports = module.exports = {};
  6. /** Initialize WebSocket server. */
  7. app._initializeWSS = function(server) {
  8. var self = this;
  9. if (this.mountpath instanceof Array) {
  10. throw new Error("This app can only be mounted on a single path");
  11. }
  12. var path = this.mountpath;
  13. var path = path + (path[path.length - 1] != '/' ? '/' : '') + 'peerjs';
  14. // Create WebSocket server as well.
  15. this._wss = new WebSocketServer({ path: path, server: server});
  16. this._wss.on('connection', function(socket) {
  17. var query = url.parse(socket.upgradeReq.url, true).query;
  18. var id = query.id;
  19. var token = query.token;
  20. var key = query.key;
  21. var ip = socket.upgradeReq.socket.remoteAddress;
  22. if (!id || !token || !key) {
  23. socket.send(JSON.stringify({ type: 'ERROR', payload: { msg: 'No id, token, or key supplied to websocket server' } }));
  24. socket.close();
  25. return;
  26. }
  27. if (!self._clients[key] || !self._clients[key][id]) {
  28. self._checkKey(key, ip, function(err) {
  29. if (!err) {
  30. if (!self._clients[key][id]) {
  31. self._clients[key][id] = { token: token, ip: ip };
  32. self._ips[ip]++;
  33. socket.send(JSON.stringify({ type: 'OPEN' }));
  34. }
  35. self._configureWS(socket, key, id, token);
  36. } else {
  37. socket.send(JSON.stringify({ type: 'ERROR', payload: { msg: err } }));
  38. }
  39. });
  40. } else {
  41. self._configureWS(socket, key, id, token);
  42. }
  43. });
  44. };
  45. app._configureWS = function(socket, key, id, token) {
  46. var self = this;
  47. var client = this._clients[key][id];
  48. if (token === client.token) {
  49. // res 'close' event will delete client.res for us
  50. client.socket = socket;
  51. // Client already exists
  52. if (client.res) {
  53. client.res.end();
  54. }
  55. } else {
  56. // ID-taken, invalid token
  57. socket.send(JSON.stringify({ type: 'ID-TAKEN', payload: { msg: 'ID is taken' } }));
  58. socket.close();
  59. return;
  60. }
  61. this._processOutstanding(key, id);
  62. // Cleanup after a socket closes.
  63. socket.on('close', function() {
  64. self._log('Socket closed:', id);
  65. if (client.socket == socket) {
  66. self._removePeer(key, id);
  67. }
  68. });
  69. // Handle messages from peers.
  70. socket.on('message', function(data) {
  71. try {
  72. var message = JSON.parse(data);
  73. if (['LEAVE', 'CANDIDATE', 'OFFER', 'ANSWER'].indexOf(message.type) !== -1) {
  74. self._handleTransmission(key, {
  75. type: message.type,
  76. src: id,
  77. dst: message.dst,
  78. payload: message.payload
  79. });
  80. } else {
  81. util.prettyError('Message unrecognized');
  82. }
  83. } catch(e) {
  84. self._log('Invalid message', data);
  85. throw e;
  86. }
  87. });
  88. // We're going to emit here, because for XHR we don't *know* when someone
  89. // disconnects.
  90. this.emit('connection', id);
  91. };
  92. app._checkAllowsDiscovery = function(key, cb) {
  93. cb(this._options.allow_discovery);
  94. };
  95. app._checkKey = function(key, ip, cb) {
  96. if (key == this._options.key) {
  97. if (!this._clients[key]) {
  98. this._clients[key] = {};
  99. }
  100. if (!this._outstanding[key]) {
  101. this._outstanding[key] = {};
  102. }
  103. if (!this._ips[ip]) {
  104. this._ips[ip] = 0;
  105. }
  106. // Check concurrent limit
  107. if (Object.keys(this._clients[key]).length >= this._options.concurrent_limit) {
  108. cb('Server has reached its concurrent user limit');
  109. return;
  110. }
  111. if (this._ips[ip] >= this._options.ip_limit) {
  112. cb(ip + ' has reached its concurrent user limit');
  113. return;
  114. }
  115. cb(null);
  116. } else {
  117. cb('Invalid key provided');
  118. }
  119. };
  120. /** Initialize HTTP server routes. */
  121. app._initializeHTTP = function() {
  122. var self = this;
  123. this.use(util.allowCrossDomain);
  124. this.get('/', function(req, res, next) {
  125. res.send(require('../app.json'));
  126. });
  127. // Retrieve guaranteed random ID.
  128. this.get('/:key/id', function(req, res, next) {
  129. res.contentType = 'text/html';
  130. res.send(self._generateClientId(req.params.key));
  131. });
  132. // Server sets up HTTP streaming when you get post an ID.
  133. this.post('/:key/:id/:token/id', function(req, res, next) {
  134. var id = req.params.id;
  135. var token = req.params.token;
  136. var key = req.params.key;
  137. var ip = req.connection.remoteAddress;
  138. if (!self._clients[key] || !self._clients[key][id]) {
  139. self._checkKey(key, ip, function(err) {
  140. if (!err && !self._clients[key][id]) {
  141. self._clients[key][id] = { token: token, ip: ip };
  142. self._ips[ip]++;
  143. self._startStreaming(res, key, id, token, true);
  144. } else {
  145. res.send(JSON.stringify({ type: 'HTTP-ERROR' }));
  146. }
  147. });
  148. } else {
  149. self._startStreaming(res, key, id, token);
  150. }
  151. });
  152. // Get a list of all peers for a key, enabled by the `allowDiscovery` flag.
  153. this.get('/:key/peers', function(req, res, next) {
  154. var key = req.params.key;
  155. if (self._clients[key]) {
  156. self._checkAllowsDiscovery(key, function(isAllowed) {
  157. if (isAllowed) {
  158. res.send(Object.keys(self._clients[key]));
  159. } else {
  160. res.send(401);
  161. }
  162. });
  163. } else {
  164. res.send(404);
  165. }
  166. });
  167. var handle = function(req, res, next) {
  168. var key = req.params.key;
  169. var id = req.params.id;
  170. var client;
  171. if (!self._clients[key] || !(client = self._clients[key][id])) {
  172. if (req.params.retry) {
  173. res.send(401);
  174. } else {
  175. // Retry this request
  176. req.params.retry = true;
  177. setTimeout(handle, 25, req, res);
  178. return;
  179. }
  180. }
  181. // Auth the req
  182. if (req.params.token !== client.token) {
  183. res.send(401);
  184. return;
  185. } else {
  186. self._handleTransmission(key, {
  187. type: req.body.type,
  188. src: id,
  189. dst: req.body.dst,
  190. payload: req.body.payload
  191. });
  192. res.send(200);
  193. }
  194. };
  195. var jsonParser = bodyParser.json();
  196. this.post('/:key/:id/:token/offer', jsonParser, handle);
  197. this.post('/:key/:id/:token/candidate', jsonParser, handle);
  198. this.post('/:key/:id/:token/answer', jsonParser, handle);
  199. this.post('/:key/:id/:token/leave', jsonParser, handle);
  200. };
  201. /** Saves a streaming response and takes care of timeouts and headers. */
  202. app._startStreaming = function(res, key, id, token, open) {
  203. var self = this;
  204. res.writeHead(200, {'Content-Type': 'application/octet-stream'});
  205. var pad = '00';
  206. for (var i = 0; i < 10; i++) {
  207. pad += pad;
  208. }
  209. res.write(pad + '\n');
  210. if (open) {
  211. res.write(JSON.stringify({ type: 'OPEN' }) + '\n');
  212. }
  213. var client = this._clients[key][id];
  214. if (token === client.token) {
  215. // Client already exists
  216. res.on('close', function() {
  217. if (client.res === res) {
  218. if (!client.socket) {
  219. // No new request yet, peer dead
  220. self._removePeer(key, id);
  221. return;
  222. }
  223. delete client.res;
  224. }
  225. });
  226. client.res = res;
  227. this._processOutstanding(key, id);
  228. } else {
  229. // ID-taken, invalid token
  230. res.end(JSON.stringify({ type: 'HTTP-ERROR' }));
  231. }
  232. };
  233. app._pruneOutstanding = function() {
  234. var keys = Object.keys(this._outstanding);
  235. for (var k = 0, kk = keys.length; k < kk; k += 1) {
  236. var key = keys[k];
  237. var dsts = Object.keys(this._outstanding[key]);
  238. for (var i = 0, ii = dsts.length; i < ii; i += 1) {
  239. var offers = this._outstanding[key][dsts[i]];
  240. var seen = {};
  241. for (var j = 0, jj = offers.length; j < jj; j += 1) {
  242. var message = offers[j];
  243. if (!seen[message.src]) {
  244. this._handleTransmission(key, { type: 'EXPIRE', src: message.dst, dst: message.src });
  245. seen[message.src] = true;
  246. }
  247. }
  248. }
  249. this._outstanding[key] = {};
  250. }
  251. };
  252. /** Cleanup */
  253. app._setCleanupIntervals = function() {
  254. var self = this;
  255. // Clean up ips every 10 minutes
  256. setInterval(function() {
  257. var keys = Object.keys(self._ips);
  258. for (var i = 0, ii = keys.length; i < ii; i += 1) {
  259. var key = keys[i];
  260. if (self._ips[key] === 0) {
  261. delete self._ips[key];
  262. }
  263. }
  264. }, 600000);
  265. // Clean up outstanding messages every 5 seconds
  266. setInterval(function() {
  267. self._pruneOutstanding();
  268. }, 5000);
  269. };
  270. /** Process outstanding peer offers. */
  271. app._processOutstanding = function(key, id) {
  272. var offers = this._outstanding[key][id];
  273. if (!offers) {
  274. return;
  275. }
  276. for (var j = 0, jj = offers.length; j < jj; j += 1) {
  277. this._handleTransmission(key, offers[j]);
  278. }
  279. delete this._outstanding[key][id];
  280. };
  281. app._removePeer = function(key, id) {
  282. if (this._clients[key] && this._clients[key][id]) {
  283. this._ips[this._clients[key][id].ip]--;
  284. delete this._clients[key][id];
  285. this.emit('disconnect', id);
  286. }
  287. };
  288. /** Handles passing on a message. */
  289. app._handleTransmission = function(key, message) {
  290. var type = message.type;
  291. var src = message.src;
  292. var dst = message.dst;
  293. var data = JSON.stringify(message);
  294. var destination = this._clients[key][dst];
  295. // User is connected!
  296. if (destination) {
  297. try {
  298. this._log(type, 'from', src, 'to', dst);
  299. if (destination.socket) {
  300. destination.socket.send(data);
  301. } else if (destination.res) {
  302. data += '\n';
  303. destination.res.write(data);
  304. } else {
  305. // Neither socket no res available. Peer dead?
  306. throw "Peer dead";
  307. }
  308. } catch (e) {
  309. // This happens when a peer disconnects without closing connections and
  310. // the associated WebSocket has not closed.
  311. // Tell other side to stop trying.
  312. this._removePeer(key, dst);
  313. this._handleTransmission(key, {
  314. type: 'LEAVE',
  315. src: dst,
  316. dst: src
  317. });
  318. }
  319. } else {
  320. // Wait for this client to connect/reconnect (XHR) for important
  321. // messages.
  322. if (type !== 'LEAVE' && type !== 'EXPIRE' && dst) {
  323. var self = this;
  324. if (!this._outstanding[key][dst]) {
  325. this._outstanding[key][dst] = [];
  326. }
  327. this._outstanding[key][dst].push(message);
  328. } else if (type === 'LEAVE' && !dst) {
  329. this._removePeer(key, src);
  330. } else {
  331. // Unavailable destination specified with message LEAVE or EXPIRE
  332. // Ignore
  333. }
  334. }
  335. };
  336. app._generateClientId = function(key) {
  337. var clientId = util.randomId();
  338. if (!this._clients[key]) {
  339. return clientId;
  340. }
  341. while (!!this._clients[key][clientId]) {
  342. clientId = util.randomId();
  343. }
  344. return clientId;
  345. };
  346. app._log = function() {
  347. if (this._options.debug) {
  348. console.log.apply(console, arguments);
  349. }
  350. };