server.js 10 KB

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