server.js 11 KB

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