-
Notifications
You must be signed in to change notification settings - Fork 3
/
snowflake.js
192 lines (173 loc) · 5.59 KB
/
snowflake.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/* global log, dbg, DummyRateLimit, BucketRateLimit, ProxyPair */
/*
A JavaScript WebRTC snowflake proxy
Uses WebRTC from the client, and Websocket to the server.
Assume that the webrtc client plugin is always the offerer, in which case
this proxy must always act as the answerer.
TODO: More documentation
*/
class Snowflake {
// Prepare the Snowflake with a Broker (to find clients) and optional UI.
constructor(config, ui, broker) {
this.receiveOffer = this.receiveOffer.bind(this);
this.config = config;
this.ui = ui;
this.broker = broker;
this.broker.setNATType(ui.natType);
this.proxyPairs = [];
this.natFailures = 0;
this.pollInterval = this.config.defaultBrokerPollInterval;
if (void 0 === this.config.rateLimitBytes) {
this.rateLimit = new DummyRateLimit();
} else {
this.rateLimit = new BucketRateLimit(this.config.rateLimitBytes * this.config.rateLimitHistory, this.config.rateLimitHistory);
}
this.retries = 0;
}
// Set the target relay address spec, which is expected to be websocket.
// TODO: Should potentially fetch the target from broker later, or modify
// entirely for the Tor-independent version.
setRelayAddr(relayAddr) {
this.relayAddr = relayAddr;
log('Using ' + relayAddr.host + ':' + relayAddr.port + ' as Relay.');
return true;
}
// Initialize WebRTC PeerConnection, which requires beginning the signalling
// process. |pollBroker| automatically arranges signalling.
beginWebRTC() {
this.pollBroker();
return this.pollTimeout = setTimeout((() => {
return this.beginWebRTC();
}), this.pollInterval);
}
// Regularly poll Broker for clients to serve until this snowflake is
// serving at capacity, at which point stop polling.
pollBroker() {
var msg, pair, recv;
// Poll broker for clients.
pair = this.makeProxyPair();
if (!pair) {
log('At client capacity.');
return;
}
log('Polling broker..');
// Do nothing until a new proxyPair is available.
msg = 'Polling for client ... ';
if (this.retries > 0) {
msg += '[retries: ' + this.retries + ']';
}
this.ui.setStatus(msg);
//update NAT type
console.log("NAT type: "+ this.ui.natType);
this.broker.setNATType(this.ui.natType);
recv = this.broker.getClientOffer(pair.id, this.proxyPairs.length);
recv.then((resp) => {
var clientNAT = resp.NAT;
if (!this.receiveOffer(pair, resp.Offer)) {
return pair.close();
}
//set a timeout for channel creation
return setTimeout((() => {
if (!pair.webrtcIsReady()) {
log('proxypair datachannel timed out waiting for open');
pair.close();
// increase poll interval
this.pollInterval =
Math.min(this.pollInterval + this.config.pollAdjustment,
this.config.slowestBrokerPollInterval);
if (clientNAT == "restricted") {
this.natFailures++;
}
// if we fail to connect to a restricted client 3 times in
// a row, assume we have a restricted NAT
if (this.natFailures >= 3){
this.ui.natType = "restricted";
console.log("Learned NAT type: restricted");
this.natFailures = 0;
}
this.broker.setNATType(this.ui.natType);
} else {
// decrease poll interval
this.pollInterval =
Math.max(this.pollInterval - this.config.pollAdjustment,
this.config.defaultBrokerPollInterval);
this.natFailures = 0;
}
return;
}), this.config.datachannelTimeout);
}, function() {
//on error, close proxy pair
return pair.close();
});
return this.retries++;
}
// Receive an SDP offer from some client assigned by the Broker,
// |pair| - an available ProxyPair.
receiveOffer(pair, desc) {
var e, offer, sdp;
try {
offer = JSON.parse(desc);
dbg('Received:\n\n' + offer.sdp + '\n');
sdp = new RTCSessionDescription(offer);
if (pair.receiveWebRTCOffer(sdp)) {
this.sendAnswer(pair);
return true;
} else {
return false;
}
} catch (error) {
e = error;
log('ERROR: Unable to receive Offer: ' + e);
return false;
}
}
sendAnswer(pair) {
var fail, next;
next = function(sdp) {
dbg('webrtc: Answer ready.');
return pair.pc.setLocalDescription(sdp).catch(fail);
};
fail = function() {
pair.close();
return dbg('webrtc: Failed to create or set Answer');
};
return pair.pc.createAnswer().then(next).catch(fail);
}
makeProxyPair() {
if (this.proxyPairs.length >= this.config.maxNumClients) {
return null;
}
var pair;
pair = new ProxyPair(this.relayAddr, this.rateLimit, this.config);
this.proxyPairs.push(pair);
log('Snowflake IDs: ' + (this.proxyPairs.map(function(p) {
return p.id;
})).join(' | '));
pair.onCleanup = () => {
var ind;
// Delete from the list of proxy pairs.
ind = this.proxyPairs.indexOf(pair);
if (ind > -1) {
return this.proxyPairs.splice(ind, 1);
}
};
pair.begin();
return pair;
}
// Stop all proxypairs.
disable() {
var results;
log('Disabling Snowflake.');
clearTimeout(this.pollTimeout);
results = [];
while (this.proxyPairs.length > 0) {
results.push(this.proxyPairs.pop().close());
}
return results;
}
}
Snowflake.prototype.relayAddr = null;
Snowflake.prototype.rateLimit = null;
Snowflake.MESSAGE = {
CONFIRMATION: 'You\'re currently serving a Tor user via Snowflake.'
};