snowflake.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. /* global log, dbg, DummyRateLimit, BucketRateLimit, SessionDescription, ProxyPair */
  2. /*
  3. A JavaScript WebRTC snowflake proxy
  4. Uses WebRTC from the client, and Websocket to the server.
  5. Assume that the webrtc client plugin is always the offerer, in which case
  6. this proxy must always act as the answerer.
  7. TODO: More documentation
  8. */
  9. // Minimum viable snowflake for now - just 1 client.
  10. class Snowflake {
  11. // Prepare the Snowflake with a Broker (to find clients) and optional UI.
  12. constructor(config, ui, broker) {
  13. // Receive an SDP offer from some client assigned by the Broker,
  14. // |pair| - an available ProxyPair.
  15. this.receiveOffer = this.receiveOffer.bind(this);
  16. this.config = config;
  17. this.ui = ui;
  18. this.broker = broker;
  19. this.state = Snowflake.MODE.INIT;
  20. this.proxyPairs = [];
  21. if (void 0 === this.config.rateLimitBytes) {
  22. this.rateLimit = new DummyRateLimit();
  23. } else {
  24. this.rateLimit = new BucketRateLimit(this.config.rateLimitBytes * this.config.rateLimitHistory, this.config.rateLimitHistory);
  25. }
  26. this.retries = 0;
  27. }
  28. // Set the target relay address spec, which is expected to be websocket.
  29. // TODO: Should potentially fetch the target from broker later, or modify
  30. // entirely for the Tor-independent version.
  31. setRelayAddr(relayAddr) {
  32. this.relayAddr = relayAddr;
  33. log('Using ' + relayAddr.host + ':' + relayAddr.port + ' as Relay.');
  34. return true;
  35. }
  36. // Initialize WebRTC PeerConnection, which requires beginning the signalling
  37. // process. |pollBroker| automatically arranges signalling.
  38. beginWebRTC() {
  39. this.state = Snowflake.MODE.WEBRTC_CONNECTING;
  40. log('ProxyPair Slots: ' + this.proxyPairs.length);
  41. log('Snowflake IDs: ' + (this.proxyPairs.map(function(p) {
  42. return p.id;
  43. })).join(' | '));
  44. this.pollBroker();
  45. return this.pollInterval = setInterval((() => {
  46. return this.pollBroker();
  47. }), this.config.defaultBrokerPollInterval);
  48. }
  49. // Regularly poll Broker for clients to serve until this snowflake is
  50. // serving at capacity, at which point stop polling.
  51. pollBroker() {
  52. var msg, pair, recv;
  53. // Poll broker for clients.
  54. pair = this.nextAvailableProxyPair();
  55. if (!pair) {
  56. log('At client capacity.');
  57. return;
  58. }
  59. // Do nothing until a new proxyPair is available.
  60. pair.active = true;
  61. msg = 'Polling for client ... ';
  62. if (this.retries > 0) {
  63. msg += '[retries: ' + this.retries + ']';
  64. }
  65. this.ui.setStatus(msg);
  66. recv = this.broker.getClientOffer(pair.id);
  67. recv.then((desc) => {
  68. if (pair.active) {
  69. if (!this.receiveOffer(pair, desc)) {
  70. return pair.active = false;
  71. }
  72. //set a timeout for channel creation
  73. return setTimeout((() => {
  74. if (!pair.running) {
  75. log('proxypair datachannel timed out waiting for open');
  76. pair.close();
  77. return pair.active = false;
  78. }
  79. }), 20000); // 20 second timeout
  80. }
  81. }, function() {
  82. return pair.active = false;
  83. });
  84. return this.retries++;
  85. }
  86. // Returns the first ProxyPair that's available to connect.
  87. nextAvailableProxyPair() {
  88. if (this.proxyPairs.length < this.config.connectionsPerClient) {
  89. return this.makeProxyPair(this.relayAddr);
  90. }
  91. return this.proxyPairs.find(function(pp) {
  92. return !pp.active;
  93. });
  94. }
  95. receiveOffer(pair, desc) {
  96. var e, offer, sdp;
  97. try {
  98. offer = JSON.parse(desc);
  99. dbg('Received:\n\n' + offer.sdp + '\n');
  100. sdp = new SessionDescription(offer);
  101. if (pair.receiveWebRTCOffer(sdp)) {
  102. this.sendAnswer(pair);
  103. return true;
  104. } else {
  105. return false;
  106. }
  107. } catch (error) {
  108. e = error;
  109. log('ERROR: Unable to receive Offer: ' + e);
  110. return false;
  111. }
  112. }
  113. sendAnswer(pair) {
  114. var fail, next;
  115. next = function(sdp) {
  116. dbg('webrtc: Answer ready.');
  117. return pair.pc.setLocalDescription(sdp).catch(fail);
  118. };
  119. fail = function() {
  120. pair.active = false
  121. return dbg('webrtc: Failed to create or set Answer');
  122. };
  123. return pair.pc.createAnswer().then(next).catch(fail);
  124. }
  125. makeProxyPair(relay) {
  126. var pair;
  127. pair = new ProxyPair(relay, this.rateLimit, this.config.pcConfig);
  128. this.proxyPairs.push(pair);
  129. pair.onCleanup = () => {
  130. var ind;
  131. // Delete from the list of active proxy pairs.
  132. ind = this.proxyPairs.indexOf(pair);
  133. if (ind > -1) {
  134. return this.proxyPairs.splice(ind, 1);
  135. }
  136. };
  137. pair.begin();
  138. return pair;
  139. }
  140. // Stop all proxypairs.
  141. disable() {
  142. var results;
  143. log('Disabling Snowflake.');
  144. clearInterval(this.pollInterval);
  145. results = [];
  146. while (this.proxyPairs.length > 0) {
  147. results.push(this.proxyPairs.pop().close());
  148. }
  149. return results;
  150. }
  151. }
  152. Snowflake.prototype.relayAddr = null;
  153. Snowflake.prototype.rateLimit = null;
  154. Snowflake.prototype.pollInterval = null;
  155. Snowflake.prototype.retries = 0;
  156. // Janky state machine
  157. Snowflake.MODE = {
  158. INIT: 0,
  159. WEBRTC_CONNECTING: 1,
  160. WEBRTC_READY: 2
  161. };
  162. Snowflake.MESSAGE = {
  163. CONFIRMATION: 'You\'re currently serving a Tor user via Snowflake.'
  164. };