server.js 10 KB

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