server.js 12 KB

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