server.js 13 KB

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