server.js 11 KB

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