server.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. var process = require('process')
  2. // Handle SIGINT
  3. process.on('SIGINT', () => {
  4. console.info("SIGINT Received, exiting...")
  5. process.exit(0)
  6. })
  7. // Handle SIGTERM
  8. process.on('SIGTERM', () => {
  9. console.info("SIGTERM Received, exiting...")
  10. process.exit(0)
  11. })
  12. const parser = require('ua-parser-js');
  13. const { uniqueNamesGenerator, animals, colors } = require('unique-names-generator');
  14. class SnapdropServer {
  15. constructor(port) {
  16. const WebSocket = require('ws');
  17. this._wss = new WebSocket.Server({ port: port });
  18. this._wss.on('connection', (socket, request) => this._onConnection(new Peer(socket, request)));
  19. this._wss.on('headers', (headers, response) => this._onHeaders(headers, response));
  20. this._rooms = {};
  21. console.log('Snapdrop is running on port', port);
  22. }
  23. _onConnection(peer) {
  24. this._joinRoom(peer);
  25. peer.socket.on('message', message => this._onMessage(peer, message));
  26. this._keepAlive(peer);
  27. // send displayName
  28. this._send(peer, {
  29. type: 'display-name',
  30. message: {
  31. displayName: peer.name.displayName,
  32. deviceName: peer.name.deviceName
  33. }
  34. });
  35. }
  36. _onHeaders(headers, response) {
  37. if (response.headers.cookie && response.headers.cookie.indexOf('peerid=') > -1) return;
  38. response.peerId = Peer.uuid();
  39. headers.push('Set-Cookie: peerid=' + response.peerId + "; SameSite=Strict; Secure");
  40. }
  41. _onMessage(sender, message) {
  42. // Try to parse message
  43. try {
  44. message = JSON.parse(message);
  45. } catch (e) {
  46. return; // TODO: handle malformed JSON
  47. }
  48. switch (message.type) {
  49. case 'disconnect':
  50. this._leaveRoom(sender);
  51. break;
  52. case 'pong':
  53. sender.lastBeat = Date.now();
  54. break;
  55. }
  56. // relay message to recipient
  57. if (message.to && this._rooms[sender.ip]) {
  58. const recipientId = message.to; // TODO: sanitize
  59. const recipient = this._rooms[sender.ip][recipientId];
  60. delete message.to;
  61. // add sender id
  62. message.sender = sender.id;
  63. this._send(recipient, message);
  64. return;
  65. }
  66. }
  67. _joinRoom(peer) {
  68. // if room doesn't exist, create it
  69. if (!this._rooms[peer.ip]) {
  70. this._rooms[peer.ip] = {};
  71. }
  72. // notify all other peers
  73. for (const otherPeerId in this._rooms[peer.ip]) {
  74. const otherPeer = this._rooms[peer.ip][otherPeerId];
  75. this._send(otherPeer, {
  76. type: 'peer-joined',
  77. peer: peer.getInfo()
  78. });
  79. }
  80. // notify peer about the other peers
  81. const otherPeers = [];
  82. for (const otherPeerId in this._rooms[peer.ip]) {
  83. otherPeers.push(this._rooms[peer.ip][otherPeerId].getInfo());
  84. }
  85. this._send(peer, {
  86. type: 'peers',
  87. peers: otherPeers
  88. });
  89. // add peer to room
  90. this._rooms[peer.ip][peer.id] = peer;
  91. }
  92. _leaveRoom(peer) {
  93. if (!this._rooms[peer.ip] || !this._rooms[peer.ip][peer.id]) return;
  94. this._cancelKeepAlive(this._rooms[peer.ip][peer.id]);
  95. // delete the peer
  96. delete this._rooms[peer.ip][peer.id];
  97. peer.socket.terminate();
  98. //if room is empty, delete the room
  99. if (!Object.keys(this._rooms[peer.ip]).length) {
  100. delete this._rooms[peer.ip];
  101. } else {
  102. // notify all other peers
  103. for (const otherPeerId in this._rooms[peer.ip]) {
  104. const otherPeer = this._rooms[peer.ip][otherPeerId];
  105. this._send(otherPeer, { type: 'peer-left', peerId: peer.id });
  106. }
  107. }
  108. }
  109. _send(peer, message) {
  110. if (!peer) return;
  111. if (this._wss.readyState !== this._wss.OPEN) return;
  112. message = JSON.stringify(message);
  113. peer.socket.send(message, error => '');
  114. }
  115. _keepAlive(peer) {
  116. this._cancelKeepAlive(peer);
  117. var timeout = 30000;
  118. if (!peer.lastBeat) {
  119. peer.lastBeat = Date.now();
  120. }
  121. if (Date.now() - peer.lastBeat > 2 * timeout) {
  122. this._leaveRoom(peer);
  123. return;
  124. }
  125. this._send(peer, { type: 'ping' });
  126. peer.timerId = setTimeout(() => this._keepAlive(peer), timeout);
  127. }
  128. _cancelKeepAlive(peer) {
  129. if (peer && peer.timerId) {
  130. clearTimeout(peer.timerId);
  131. }
  132. }
  133. }
  134. class Peer {
  135. constructor(socket, request) {
  136. // set socket
  137. this.socket = socket;
  138. // set remote ip
  139. this._setIP(request);
  140. // set peer id
  141. this._setPeerId(request)
  142. // is WebRTC supported ?
  143. this.rtcSupported = request.url.indexOf('webrtc') > -1;
  144. // set name
  145. this._setName(request);
  146. // for keepalive
  147. this.timerId = 0;
  148. this.lastBeat = Date.now();
  149. }
  150. _setIP(request) {
  151. if (request.headers['x-forwarded-for']) {
  152. this.ip = request.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
  153. } else {
  154. this.ip = request.connection.remoteAddress;
  155. }
  156. // IPv4 and IPv6 use different values to refer to localhost
  157. if (this.ip == '::1' || this.ip == '::ffff:127.0.0.1') {
  158. this.ip = '127.0.0.1';
  159. }
  160. }
  161. _setPeerId(request) {
  162. if (request.peerId) {
  163. this.id = request.peerId;
  164. } else {
  165. this.id = request.headers.cookie.replace('peerid=', '');
  166. }
  167. }
  168. toString() {
  169. return `<Peer id=${this.id} ip=${this.ip} rtcSupported=${this.rtcSupported}>`
  170. }
  171. _setName(req) {
  172. let ua = parser(req.headers['user-agent']);
  173. let deviceName = '';
  174. if (ua.os && ua.os.name) {
  175. deviceName = ua.os.name.replace('Mac OS', 'Mac') + ' ';
  176. }
  177. if (ua.device.model) {
  178. deviceName += ua.device.model;
  179. } else {
  180. deviceName += ua.browser.name;
  181. }
  182. if(!deviceName)
  183. deviceName = 'Unknown Device';
  184. const displayName = uniqueNamesGenerator({
  185. length: 2,
  186. separator: ' ',
  187. dictionaries: [colors, animals],
  188. style: 'capital',
  189. seed: this.id.hashCode()
  190. })
  191. this.name = {
  192. model: ua.device.model,
  193. os: ua.os.name,
  194. browser: ua.browser.name,
  195. type: ua.device.type,
  196. deviceName,
  197. displayName
  198. };
  199. }
  200. getInfo() {
  201. return {
  202. id: this.id,
  203. name: this.name,
  204. rtcSupported: this.rtcSupported
  205. }
  206. }
  207. // return uuid of form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  208. static uuid() {
  209. let uuid = '',
  210. ii;
  211. for (ii = 0; ii < 32; ii += 1) {
  212. switch (ii) {
  213. case 8:
  214. case 20:
  215. uuid += '-';
  216. uuid += (Math.random() * 16 | 0).toString(16);
  217. break;
  218. case 12:
  219. uuid += '-';
  220. uuid += '4';
  221. break;
  222. case 16:
  223. uuid += '-';
  224. uuid += (Math.random() * 4 | 8).toString(16);
  225. break;
  226. default:
  227. uuid += (Math.random() * 16 | 0).toString(16);
  228. }
  229. }
  230. return uuid;
  231. };
  232. }
  233. Object.defineProperty(String.prototype, 'hashCode', {
  234. value: function() {
  235. var hash = 0, i, chr;
  236. for (i = 0; i < this.length; i++) {
  237. chr = this.charCodeAt(i);
  238. hash = ((hash << 5) - hash) + chr;
  239. hash |= 0; // Convert to 32bit integer
  240. }
  241. return hash;
  242. }
  243. });
  244. const server = new SnapdropServer(process.env.PORT || 3000);
  245. var express = require('express')
  246. var serveStatic = require('serve-static')
  247. var client = express()
  248. client.use(serveStatic('client', { 'index': ['index.html', 'index.htm'] }))
  249. client.listen(8080)