forked from PrismarineJS/net-browserify
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbrowser.js
More file actions
571 lines (494 loc) · 15.1 KB
/
browser.js
File metadata and controls
571 lines (494 loc) · 15.1 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
var stream = require('stream');
var util = require('util');
var timers = require('timers');
var http = require('http');
var debug = util.debuglog('net');
var defaultProxy = {
protocol: (window.location.protocol == 'https:') ? 'wss' : 'ws',
requestProtocol: '',
hostname: window.location.hostname,
port: window.location.port,
path: '/api/vm/net',
headers: {},
artificialDelay: 0
};
var proxy = { ...defaultProxy }
function getProxy() {
return proxy;
}
function getProxyHost() {
var host = getProxy().hostname;
if (getProxy().port) {
host += ':'+getProxy().port;
}
return host;
}
function getProxyOrigin() {
if (getProxy().requestProtocol) {
proxy.protocol = getProxy().requestProtocol === 'https:' ? 'wss' : 'ws'
}
return getProxy().protocol + '://' + getProxyHost();
}
function getArtificialDelay() {
const delay = getProxy().artificialDelay;
if (Array.isArray(delay) && delay.length === 2) {
// Random delay between min and max values
return Math.random() * (delay[1] - delay[0]) + delay[0];
}
return delay || 0;
}
function getMaxArtificialDelay() {
const delay = getProxy().artificialDelay;
if (Array.isArray(delay) && delay.length === 2) {
// Use max value for connection closing operations
return delay[1];
}
return delay || 0;
}
exports.setProxy = function (options) {
proxy = { ...defaultProxy }
options = options || {};
let { hostname } = options
if (hostname) {
let requestProtocol
if (hostname.startsWith('http://')) {
requestProtocol = 'http:';
hostname = hostname.slice(7);
} else if (hostname.startsWith('https://')) {
requestProtocol = 'https:';
hostname = hostname.slice(8);
}
proxy.requestProtocol = requestProtocol;
proxy.hostname = hostname;
}
if (options.port) {
proxy.port = options.port;
}
if (options.path) {
proxy.path = options.path;
}
if (options.headers) {
proxy.headers = options.headers;
}
if (options.artificialDelay !== undefined) {
proxy.artificialDelay = options.artificialDelay;
}
};
exports.createServer = function () {
throw new Error('Cannot create server in a browser');
};
exports.connect = exports.createConnection = function (/* options, connectListener */) {
var args = normalizeConnectArgs(arguments);
debug('createConnection', args);
var s = new Socket(args[0]);
return Socket.prototype.connect.apply(s, args);
};
function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; }
function isPipeName(s) {
return util.isString(s) && toNumber(s) === false;
}
// Returns an array [options] or [options, cb]
// It is the same as the argument of Socket.prototype.connect().
function normalizeConnectArgs(args) {
var options = {};
if (util.isObject(args[0])) {
// connect(options, [cb])
options = args[0];
} else if (isPipeName(args[0])) {
// connect(path, [cb]);
options.path = args[0];
} else {
// connect(port, [host], [cb])
options.port = args[0];
if (util.isString(args[1])) {
options.host = args[1];
}
}
var cb = args[args.length - 1];
return util.isFunction(cb) ? [options, cb] : [options];
}
exports._normalizeConnectArgs = normalizeConnectArgs;
function Socket(options) {
if (!(this instanceof Socket)) return new Socket(options);
this._connecting = false;
this._host = null;
if (util.isNumber(options))
options = { fd: options }; // Legacy interface.
else if (util.isUndefined(options))
options = {};
stream.Duplex.call(this, options);
// these will be set once there is a connection
this.readable = this.writable = false;
// handle strings directly
this._writableState.decodeStrings = false;
// default to *not* allowing half open sockets
this.allowHalfOpen = options && options.allowHalfOpen || false;
// Set default timeout to 10 seconds if not specified
this._wsTimeout = options && options.wsTimeout || 10000;
}
util.inherits(Socket, stream.Duplex);
exports.Socket = Socket;
exports.Stream = Socket; // Legacy naming.
Socket.prototype.listen = function () {
throw new Error('Cannot listen in a browser');
};
Socket.prototype.setTimeout = function (msecs, callback) {
if (msecs > 0 && isFinite(msecs)) {
timers.enroll(this, msecs);
//timers._unrefActive(this);
if (callback) {
this.once('timeout', callback);
}
} else if (msecs === 0) {
timers.unenroll(this);
if (callback) {
this.removeListener('timeout', callback);
}
}
};
Socket.prototype._onTimeout = function () {
debug('_onTimeout');
this.emit('timeout');
};
Socket.prototype.setNoDelay = function (enable) {};
Socket.prototype.setKeepAlive = function (setting, msecs) {};
Socket.prototype.address = function () {
return {
address: this.remoteAddress,
port: this.remotePort,
family: this.remoteFamily
};
};
Object.defineProperty(Socket.prototype, 'readyState', {
get: function() {
if (this._connecting) {
return 'opening';
} else if (this.readable && this.writable) {
return 'open';
} else if (this.readable && !this.writable) {
return 'readOnly';
} else if (!this.readable && this.writable) {
return 'writeOnly';
} else {
return 'closed';
}
}
});
Socket.prototype.bufferSize = undefined;
Socket.prototype._read = function () {};
Socket.prototype.end = function(data, encoding) {
stream.Duplex.prototype.end.call(this, data, encoding);
this.writable = false;
if (this._ws) {
const delay = getMaxArtificialDelay();
if (delay > 0) {
setTimeout(() => {
this._ws.close();
}, delay);
} else {
this._ws.close();
}
}
// just in case we're waiting for an EOF.
if (this.readable && !this._readableState.endEmitted)
this.read(0);
else
maybeDestroy(this);
};
// Call whenever we set writable=false or readable=false
function maybeDestroy(socket) {
if (!socket.readable &&
!socket.writable &&
!socket.destroyed &&
!socket._connecting &&
!socket._writableState.length) {
socket.destroy();
}
}
Socket.prototype.destroySoon = function() {
if (this.writable)
this.end();
if (this._writableState.finished)
this.destroy();
else
this.once('finish', this.destroy);
};
Socket.prototype.destroy = function(exception) {
debug('destroy', exception);
if (this.destroyed) {
return;
}
this._connecting = false;
this.readable = this.writable = false;
timers.unenroll(this);
debug('close');
this.destroyed = true;
};
Socket.prototype.remoteAddress = null;
Socket.prototype.remoteFamily = null;
Socket.prototype.remotePort = null;
// Used for servers only - not here
Socket.prototype.localAddress = null;
Socket.prototype.localPort = null;
Socket.prototype.bytesRead = 0;
Socket.prototype.bytesWritten = 0;
Socket.prototype._write = function (data, encoding, cb) {
var self = this;
cb = cb || function () {};
// If we are still connecting, then buffer this for later.
// The Writable logic will buffer up any more writes while
// waiting for this one to be done.
if (this._connecting) {
this._pendingData = data;
this._pendingEncoding = encoding;
this.once('connect', function() {
this._write(data, encoding, cb);
});
return;
}
this._pendingData = null;
this._pendingEncoding = '';
if (encoding == 'binary' && typeof data == 'string') { //TODO: maybe apply this for all string inputs?
// Setting encoding is very important for binary data - otherwise the data gets modified
data = new Buffer(data, encoding);
}
// Send the data
const delay = getArtificialDelay();
if (delay > 0) {
setTimeout(() => {
this._ws.send(data);
}, delay);
} else {
this._ws.send(data);
}
process.nextTick(function () {
//console.log('[tcp] sent: ', data.toString(), data.length);
self.bytesWritten += data.length;
cb();
});
};
Socket.prototype.write = function(chunk, encoding, cb) {
if (!util.isString(chunk) && !util.isBuffer(chunk))
throw new TypeError('invalid data');
return stream.Duplex.prototype.write.apply(this, arguments);
};
Socket.prototype.connect = function(options, cb) {
var self = this;
if (!util.isObject(options)) {
// Old API:
// connect(port, [host], [cb])
// connect(path, [cb]);
var args = normalizeConnectArgs(arguments);
return Socket.prototype.connect.apply(this, args);
}
cb = cb || function () {};
if (this.write !== Socket.prototype.write)
this.write = Socket.prototype.write;
if (options.path) {
throw new Error('options.path not supported in the browser');
}
self._connecting = true;
self.writable = true;
self._host = options.host;
let timedOut = false
let timeout
var req = http.request({
hostname: getProxy().hostname,
port: getProxy().port,
path: getProxy().path + '/connect',
protocol: getProxy().requestProtocol,
method: 'POST',
withCredentials: false,
headers: {
'Content-Type': 'application/json',
...getProxy().headers
}
}, function (res) {
if (timedOut) return
clearTimeout(timeout)
var json = '';
res.on('data', function (buf) {
json += buf;
});
res.on('end', function () {
var data = null;
try {
data = JSON.parse(json);
} catch (e) {
data = {
code: res.statusCode,
error: json
};
}
if (data.error !== undefined) {
let errorMessage = 'Cannot open TCP connection ['+res.statusCode+']: '+JSON.stringify(data.error)
if (res.statusCode === 0) {
errorMessage = `Cannot reach the proxy server ${getProxy().hostname}:${getProxy().port}`
} else if (res.statusCode === 404) {
errorMessage = 'Cannot find the proxy server (404). Check proxy ip you entered.'
}
if (data.error.code === 'ENOTFOUND') {
errorMessage = 'Cannot find the server. Check server ip you entered.'
}
self.emit('error', errorMessage);
self.destroy();
return;
}
self.remoteAddress = data.remote.address;
self.remoteFamily = data.remote.family;
self.remotePort = data.remote.port;
self._connectWebSocket(data.token, function (err) {
if (err) {
cb(err);
return;
}
cb();
});
});
});
timeout = setTimeout(() => {
if (!timedOut) {
timedOut = true
req.xhr.abort()
self.emit('error', `Timeout for connecting to proxy ${getProxy().hostname}:${getProxy().port}. Make sure it is reachable: try opening it in your browser or use alternative proxy server.`)
self.destroy()
}
}, 10_000)
req.setHeader('Content-Type', 'application/json');
// Set additional headers from proxy configuration
Object.entries(getProxy().headers).forEach(([key, value]) => {
req.setHeader(key, value);
});
req.write(JSON.stringify(options));
req.end();
return this;
};
Socket.prototype._connectWebSocket = function (token, cb) {
var self = this;
if (self._ws) {
process.nextTick(function () {
cb();
});
return;
}
this._ws = new WebSocket(getProxyOrigin() + getProxy().path + '/socket?token='+token);
this._handleWebsocket();
if (cb) {
self.on('connect', cb);
}
};
Socket.prototype.handleStringMessage = function (message) {
return false
}
Socket.prototype._handleWebsocket = function () {
var self = this;
// Add connection timeout
let timedOut = false;
const timeout = setTimeout(() => {
if (!timedOut) {
timedOut = true;
if (self._ws) {
self._ws.close();
}
const error = `Proxy server is reachable, but the WebSocket connection timed out after ${this._wsTimeout / 1000} seconds. Possible reasons:
1. Most probably the proxy server (${getProxy().hostname}:${getProxy().port}) is misconfigured and not accepting WebSocket connections.
2. Your browser or network is blocking WebSocket connections.`;
self.emit('error', error);
}
}, this._wsTimeout);
this._ws.addEventListener('open', function () {
if (timedOut) return;
clearTimeout(timeout);
//console.log('TCP OK');
self._connecting = false;
self.readable = true;
self.emit('connect');
self.read(0);
});
this._ws.addEventListener('error', function (e) {
if (timedOut) return;
clearTimeout(timeout);
// `e` doesn't contain anything useful (https://developer.mozilla.org/en/docs/WebSockets/Writing_WebSocket_client_applications#Connection_errors)
console.warn('TCP error', e);
self.emit('error', 'An error occurred with the WebSocket connection. Please check your network connection and proxy server status.');
});
let reading = false
this._ws.addEventListener('message', function (e) {
var contents = e.data;
var gotBuffer = function (buffer) {
//console.log('[tcp] received: ' + buffer.toString(), buffer.length);
self.bytesRead += buffer.length;
self.push(buffer);
};
var processBuffer = function (buffer) {
const delay = getArtificialDelay();
if (delay > 0) {
setTimeout(() => {
gotBuffer(buffer);
}, delay);
} else {
gotBuffer(buffer);
}
};
if (typeof contents == 'string') {
if (contents.startsWith('pong:')) {
self.emit('pong', contents.slice('pong:'.length));
return
}
if (self.handleStringMessage(contents)) {
var buffer = new Buffer(contents);
processBuffer(buffer);
}
} else if (window.Blob && contents instanceof Blob) {
var fileReader = new FileReader();
let resolveReading
reading = new Promise((resolve) => {
resolveReading = resolve
})
fileReader.addEventListener('load', function (e) {
var buf = fileReader.result;
var arr = new Uint8Array(buf);
processBuffer(new Buffer(arr));
resolveReading()
reading = false
});
fileReader.addEventListener('error', function (e) {
console.warn('Cannot read TCP stream: file reader error', e);
resolveReading()
reading = false
});
fileReader.readAsArrayBuffer(contents);
} else {
console.warn('Cannot read TCP stream: unsupported message type', contents);
}
});
this._ws.addEventListener('close', async function () {
if (self.readyState == 'open') {
//console.log('TCP closed');
await reading
const delay = getMaxArtificialDelay();
if (delay > 0) {
setTimeout(() => {
self.destroy();
}, delay);
} else {
self.destroy();
}
}
});
};
exports.isIP = function (input) {
if (exports.isIPv4(input)) {
return 4;
} else if (exports.isIPv6(input)) {
return 6;
} else {
return 0;
}
};
exports.isIPv4 = function(input) {
return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(input);
};
exports.isIPv6 = function(input) {
return /^(([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-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