server.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. this._wss.on("error", function (err) {
  51. // handle error
  52. })
  53. };
  54. app._configureWS = function(socket, key, id, token) {
  55. var self = this;
  56. var client = this._clients[key][id];
  57. if (token === client.token) {
  58. // res 'close' event will delete client.res for us
  59. client.socket = socket;
  60. // Client already exists
  61. if (client.res) {
  62. client.res.end();
  63. }
  64. } else {
  65. // ID-taken, invalid token
  66. socket.send(
  67. JSON.stringify({ type: "ID-TAKEN", payload: { msg: "ID is taken" } })
  68. );
  69. socket.close();
  70. return;
  71. }
  72. this._processOutstanding(key, id);
  73. // Cleanup after a socket closes.
  74. socket.on("close", function() {
  75. self._log("Socket closed:", id);
  76. if (client.socket == socket) {
  77. self._removePeer(key, id);
  78. }
  79. });
  80. // Handle messages from peers.
  81. socket.on("message", function(data) {
  82. try {
  83. var message = JSON.parse(data);
  84. if (
  85. ["LEAVE", "CANDIDATE", "OFFER", "ANSWER"].indexOf(message.type) !== -1
  86. ) {
  87. self._handleTransmission(key, {
  88. type: message.type,
  89. src: id,
  90. dst: message.dst,
  91. payload: message.payload
  92. });
  93. } else if (message.type === 'HEARTBEAT') {
  94. // Ignore - nothing needs doing here.
  95. } else {
  96. util.prettyError("Message unrecognized");
  97. }
  98. } catch (e) {
  99. self._log("Invalid message", data);
  100. throw e;
  101. }
  102. });
  103. // We're going to emit here, because for XHR we don't *know* when someone
  104. // disconnects.
  105. this.emit("connection", id);
  106. };
  107. app._checkAllowsDiscovery = function(key, cb) {
  108. cb(this._options.allow_discovery);
  109. };
  110. app._checkKey = function(key, ip, cb) {
  111. if (key == this._options.key) {
  112. if (!this._clients[key]) {
  113. this._clients[key] = {};
  114. }
  115. if (!this._outstanding[key]) {
  116. this._outstanding[key] = {};
  117. }
  118. if (!this._ips[ip]) {
  119. this._ips[ip] = 0;
  120. }
  121. // Check concurrent limit
  122. if (
  123. Object.keys(this._clients[key]).length >= this._options.concurrent_limit
  124. ) {
  125. cb("Server has reached its concurrent user limit");
  126. return;
  127. }
  128. if (this._ips[ip] >= this._options.ip_limit) {
  129. cb(ip + " has reached its concurrent user limit");
  130. return;
  131. }
  132. cb(null);
  133. } else {
  134. cb("Invalid key provided");
  135. }
  136. };
  137. /** Initialize HTTP server routes. */
  138. app._initializeHTTP = function() {
  139. var self = this;
  140. this.use(cors());
  141. this.get("/", function(req, res, next) {
  142. res.send(require("../app.json"));
  143. });
  144. // Retrieve guaranteed random ID.
  145. this.get("/:key/id", function(req, res, next) {
  146. res.contentType = "text/html";
  147. res.send(self._generateClientId(req.params.key));
  148. });
  149. // Server sets up HTTP streaming when you get post an ID.
  150. this.post("/:key/:id/:token/id", function(req, res, next) {
  151. var id = req.params.id;
  152. var token = req.params.token;
  153. var key = req.params.key;
  154. var ip = req.connection.remoteAddress;
  155. if (!self._clients[key] || !self._clients[key][id]) {
  156. self._checkKey(key, ip, function(err) {
  157. if (!err && !self._clients[key][id]) {
  158. self._clients[key][id] = { token: token, ip: ip };
  159. self._ips[ip]++;
  160. self._startStreaming(res, key, id, token, true);
  161. } else {
  162. res.send(JSON.stringify({ type: "HTTP-ERROR" }));
  163. }
  164. });
  165. } else {
  166. self._startStreaming(res, key, id, token);
  167. }
  168. });
  169. // Get a list of all peers for a key, enabled by the `allowDiscovery` flag.
  170. this.get("/:key/peers", function(req, res, next) {
  171. var key = req.params.key;
  172. if (self._clients[key]) {
  173. self._checkAllowsDiscovery(key, function(isAllowed) {
  174. if (isAllowed) {
  175. res.send(Object.keys(self._clients[key]));
  176. } else {
  177. res.sendStatus(401);
  178. }
  179. });
  180. } else {
  181. res.sendStatus(404);
  182. }
  183. });
  184. var handle = function(req, res, next) {
  185. var key = req.params.key;
  186. var id = req.params.id;
  187. var client;
  188. if (!self._clients[key] || !(client = self._clients[key][id])) {
  189. if (req.params.retry) {
  190. res.sendStatus(401);
  191. return;
  192. } else {
  193. // Retry this request
  194. req.params.retry = true;
  195. setTimeout(handle, 25, req, res);
  196. return;
  197. }
  198. }
  199. // Auth the req
  200. if (client.token && req.params.token !== client.token) {
  201. res.sendStatus(401);
  202. return;
  203. } else {
  204. self._handleTransmission(key, {
  205. type: req.body.type,
  206. src: id,
  207. dst: req.body.dst,
  208. payload: req.body.payload
  209. });
  210. res.sendStatus(200);
  211. }
  212. };
  213. var jsonParser = bodyParser.json();
  214. this.post("/:key/:id/:token/offer", jsonParser, handle);
  215. this.post("/:key/:id/:token/candidate", jsonParser, handle);
  216. this.post("/:key/:id/:token/answer", jsonParser, handle);
  217. this.post("/:key/:id/:token/leave", jsonParser, handle);
  218. };
  219. /** Saves a streaming response and takes care of timeouts and headers. */
  220. app._startStreaming = function(res, key, id, token, open) {
  221. var self = this;
  222. res.writeHead(200, { "Content-Type": "application/octet-stream" });
  223. var pad = "00";
  224. for (var i = 0; i < 10; i++) {
  225. pad += pad;
  226. }
  227. res.write(pad + "\n");
  228. if (open) {
  229. res.write(JSON.stringify({ type: "OPEN" }) + "\n");
  230. }
  231. var client = this._clients[key][id];
  232. if (token === client.token) {
  233. // Client already exists
  234. res.on("close", function() {
  235. if (client.res === res) {
  236. if (!client.socket) {
  237. // No new request yet, peer dead
  238. self._removePeer(key, id);
  239. return;
  240. }
  241. delete client.res;
  242. }
  243. });
  244. client.res = res;
  245. this._processOutstanding(key, id);
  246. } else {
  247. // ID-taken, invalid token
  248. res.end(JSON.stringify({ type: "HTTP-ERROR" }));
  249. }
  250. };
  251. app._pruneOutstanding = function() {
  252. var keys = Object.keys(this._outstanding);
  253. for (var k = 0, kk = keys.length; k < kk; k += 1) {
  254. var key = keys[k];
  255. var dsts = Object.keys(this._outstanding[key]);
  256. for (var i = 0, ii = dsts.length; i < ii; i += 1) {
  257. var offers = this._outstanding[key][dsts[i]];
  258. var seen = {};
  259. for (var j = 0, jj = offers.length; j < jj; j += 1) {
  260. var message = offers[j];
  261. if (!seen[message.src]) {
  262. this._handleTransmission(key, {
  263. type: "EXPIRE",
  264. src: message.dst,
  265. dst: message.src
  266. });
  267. seen[message.src] = true;
  268. }
  269. }
  270. }
  271. this._outstanding[key] = {};
  272. }
  273. };
  274. /** Cleanup */
  275. app._setCleanupIntervals = function() {
  276. var self = this;
  277. // Clean up ips every 10 minutes
  278. setInterval(function() {
  279. var keys = Object.keys(self._ips);
  280. for (var i = 0, ii = keys.length; i < ii; i += 1) {
  281. var key = keys[i];
  282. if (self._ips[key] === 0) {
  283. delete self._ips[key];
  284. }
  285. }
  286. }, 600000);
  287. // Clean up outstanding messages every 5 seconds
  288. setInterval(function() {
  289. self._pruneOutstanding();
  290. }, 5000);
  291. };
  292. /** Process outstanding peer offers. */
  293. app._processOutstanding = function(key, id) {
  294. var offers = this._outstanding[key][id];
  295. if (!offers) {
  296. return;
  297. }
  298. for (var j = 0, jj = offers.length; j < jj; j += 1) {
  299. this._handleTransmission(key, offers[j]);
  300. }
  301. delete this._outstanding[key][id];
  302. };
  303. app._removePeer = function(key, id) {
  304. if (this._clients[key] && this._clients[key][id]) {
  305. this._ips[this._clients[key][id].ip]--;
  306. delete this._clients[key][id];
  307. this.emit("disconnect", id);
  308. }
  309. };
  310. /** Handles passing on a message. */
  311. app._handleTransmission = function(key, message) {
  312. var type = message.type;
  313. var src = message.src;
  314. var dst = message.dst;
  315. var data = JSON.stringify(message);
  316. var destination = this._clients[key][dst];
  317. // User is connected!
  318. if (destination) {
  319. try {
  320. this._log(type, "from", src, "to", dst);
  321. if (destination.socket) {
  322. destination.socket.send(data);
  323. } else if (destination.res) {
  324. data += "\n";
  325. destination.res.write(data);
  326. } else {
  327. // Neither socket no res available. Peer dead?
  328. throw "Peer dead";
  329. }
  330. } catch (e) {
  331. // This happens when a peer disconnects without closing connections and
  332. // the associated WebSocket has not closed.
  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. app._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. app._log = function() {
  369. if (this._options.debug) {
  370. console.log.apply(console, arguments);
  371. }
  372. };