server.js 12 KB

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