server.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. util.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. util.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. // Retrieve guaranteed random ID.
  125. this.get('/:key/id', function(req, res, next) {
  126. res.contentType = 'text/html';
  127. res.send(self._generateClientId(req.params.key));
  128. });
  129. // Server sets up HTTP streaming when you get post an ID.
  130. this.post('/:key/:id/:token/id', function(req, res, next) {
  131. var id = req.params.id;
  132. var token = req.params.token;
  133. var key = req.params.key;
  134. var ip = req.connection.remoteAddress;
  135. if (!self._clients[key] || !self._clients[key][id]) {
  136. self._checkKey(key, ip, function(err) {
  137. if (!err && !self._clients[key][id]) {
  138. self._clients[key][id] = { token: token, ip: ip };
  139. self._ips[ip]++;
  140. self._startStreaming(res, key, id, token, true);
  141. } else {
  142. res.send(JSON.stringify({ type: 'HTTP-ERROR' }));
  143. }
  144. });
  145. } else {
  146. self._startStreaming(res, key, id, token);
  147. }
  148. });
  149. // Get a list of all peers for a key, enabled by the `allowDiscovery` flag.
  150. this.get('/:key/peers', function(req, res, next) {
  151. var key = req.params.key;
  152. if (self._clients[key]) {
  153. self._checkAllowsDiscovery(key, function(isAllowed) {
  154. if (isAllowed) {
  155. res.send(Object.keys(self._clients[key]));
  156. } else {
  157. res.send(401);
  158. }
  159. });
  160. } else {
  161. res.send(404);
  162. }
  163. });
  164. var handle = function(req, res, next) {
  165. var key = req.params.key;
  166. var id = req.params.id;
  167. var client;
  168. if (!self._clients[key] || !(client = self._clients[key][id])) {
  169. if (req.params.retry) {
  170. res.send(401);
  171. } else {
  172. // Retry this request
  173. req.params.retry = true;
  174. setTimeout(handle, 25, req, res);
  175. return;
  176. }
  177. }
  178. // Auth the req
  179. if (req.params.token !== client.token) {
  180. res.send(401);
  181. return;
  182. } else {
  183. self._handleTransmission(key, {
  184. type: req.body.type,
  185. src: id,
  186. dst: req.body.dst,
  187. payload: req.body.payload
  188. });
  189. res.send(200);
  190. }
  191. };
  192. var jsonParser = bodyParser.json();
  193. this.post('/:key/:id/:token/offer', jsonParser, handle);
  194. this.post('/:key/:id/:token/candidate', jsonParser, handle);
  195. this.post('/:key/:id/:token/answer', jsonParser, handle);
  196. this.post('/:key/:id/:token/leave', jsonParser, handle);
  197. };
  198. /** Saves a streaming response and takes care of timeouts and headers. */
  199. app._startStreaming = function(res, key, id, token, open) {
  200. var self = this;
  201. res.writeHead(200, {'Content-Type': 'application/octet-stream'});
  202. var pad = '00';
  203. for (var i = 0; i < 10; i++) {
  204. pad += pad;
  205. }
  206. res.write(pad + '\n');
  207. if (open) {
  208. res.write(JSON.stringify({ type: 'OPEN' }) + '\n');
  209. }
  210. var client = this._clients[key][id];
  211. if (token === client.token) {
  212. // Client already exists
  213. res.on('close', function() {
  214. if (client.res === res) {
  215. if (!client.socket) {
  216. // No new request yet, peer dead
  217. self._removePeer(key, id);
  218. return;
  219. }
  220. delete client.res;
  221. }
  222. });
  223. client.res = res;
  224. this._processOutstanding(key, id);
  225. } else {
  226. // ID-taken, invalid token
  227. res.end(JSON.stringify({ type: 'HTTP-ERROR' }));
  228. }
  229. };
  230. app._pruneOutstanding = function() {
  231. var keys = Object.keys(this._outstanding);
  232. for (var k = 0, kk = keys.length; k < kk; k += 1) {
  233. var key = keys[k];
  234. var dsts = Object.keys(this._outstanding[key]);
  235. for (var i = 0, ii = dsts.length; i < ii; i += 1) {
  236. var offers = this._outstanding[key][dsts[i]];
  237. var seen = {};
  238. for (var j = 0, jj = offers.length; j < jj; j += 1) {
  239. var message = offers[j];
  240. if (!seen[message.src]) {
  241. this._handleTransmission(key, { type: 'EXPIRE', src: message.dst, dst: message.src });
  242. seen[message.src] = true;
  243. }
  244. }
  245. }
  246. this._outstanding[key] = {};
  247. }
  248. };
  249. /** Cleanup */
  250. app._setCleanupIntervals = function() {
  251. var self = this;
  252. // Clean up ips every 10 minutes
  253. setInterval(function() {
  254. var keys = Object.keys(self._ips);
  255. for (var i = 0, ii = keys.length; i < ii; i += 1) {
  256. var key = keys[i];
  257. if (self._ips[key] === 0) {
  258. delete self._ips[key];
  259. }
  260. }
  261. }, 600000);
  262. // Clean up outstanding messages every 5 seconds
  263. setInterval(function() {
  264. self._pruneOutstanding();
  265. }, 5000);
  266. };
  267. /** Process outstanding peer offers. */
  268. app._processOutstanding = function(key, id) {
  269. var offers = this._outstanding[key][id];
  270. if (!offers) {
  271. return;
  272. }
  273. for (var j = 0, jj = offers.length; j < jj; j += 1) {
  274. this._handleTransmission(key, offers[j]);
  275. }
  276. delete this._outstanding[key][id];
  277. };
  278. app._removePeer = function(key, id) {
  279. if (this._clients[key] && this._clients[key][id]) {
  280. this._ips[this._clients[key][id].ip]--;
  281. delete this._clients[key][id];
  282. this.emit('disconnect', id);
  283. }
  284. };
  285. /** Handles passing on a message. */
  286. app._handleTransmission = function(key, message) {
  287. var type = message.type;
  288. var src = message.src;
  289. var dst = message.dst;
  290. var data = JSON.stringify(message);
  291. var destination = this._clients[key][dst];
  292. // User is connected!
  293. if (destination) {
  294. try {
  295. util.log(type, 'from', src, 'to', dst);
  296. if (destination.socket) {
  297. destination.socket.send(data);
  298. } else if (destination.res) {
  299. data += '\n';
  300. destination.res.write(data);
  301. } else {
  302. // Neither socket no res available. Peer dead?
  303. throw "Peer dead";
  304. }
  305. } catch (e) {
  306. // This happens when a peer disconnects without closing connections and
  307. // the associated WebSocket has not closed.
  308. util.prettyError(e);
  309. // Tell other side to stop trying.
  310. this._removePeer(key, dst);
  311. this._handleTransmission(key, {
  312. type: 'LEAVE',
  313. src: dst,
  314. dst: src
  315. });
  316. }
  317. } else {
  318. // Wait for this client to connect/reconnect (XHR) for important
  319. // messages.
  320. if (type !== 'LEAVE' && type !== 'EXPIRE' && dst) {
  321. var self = this;
  322. if (!this._outstanding[key][dst]) {
  323. this._outstanding[key][dst] = [];
  324. }
  325. this._outstanding[key][dst].push(message);
  326. } else if (type === 'LEAVE' && !dst) {
  327. this._removePeer(key, src);
  328. } else {
  329. // Unavailable destination specified with message LEAVE or EXPIRE
  330. // Ignore
  331. }
  332. }
  333. };
  334. app._generateClientId = function(key) {
  335. var clientId = util.randomId();
  336. if (!this._clients[key]) {
  337. return clientId;
  338. }
  339. while (!!this._clients[key][clientId]) {
  340. clientId = util.randomId();
  341. }
  342. return clientId;
  343. };