server.js 11 KB

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