-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsocket.js
More file actions
347 lines (341 loc) · 12.5 KB
/
socket.js
File metadata and controls
347 lines (341 loc) · 12.5 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
// node-reliable-udp
// Karol Walasek
// https://github.com/WalasPrime/node-reliable-udp
const Session = require('./session');
const Timeout = require('./timeout');
const {DATAGRAM_CODES, PROTOCOL_ID} = require('./const');
const crypto = require('crypto');
const stun = require('stun');
const EventEmitter = require('events');
const dgram = require('dgram');
const dns = require('dns');
const debug = {
stun: require('debug')('reliable-udp:stun'),
udp: require('debug')('reliable-udp:udp'),
socket: require('debug')('reliable-udp:socket'),
dns: require('debug')('reliable-udp:dns')
};
const { STUN_BINDING_REQUEST, STUN_ATTR_XOR_MAPPED_ADDRESS } = stun.constants;
/**
* @class
* The main class that allows establishing reliable data streams with other hosts. Serves as a sender and receiver.
*/
class ReliableUDPSocket extends EventEmitter {
/**
* @constructor
* @param {Object} [options] Pass options to the constructor.
* @param {String} [options.address=0.0.0.0] IP address to bind to, defaults to an equivalent of _listen to any addresses_.
* @param {Number} [options.port=0] Port number to bind to, defaults to `0` which is interpreted as a random port.
* @param {Socket} [options.socket=null] An already bound socket to take over.
*/
constructor(options){
super();
this.seed = Math.random()*0xFFFFFFFF >>> 0;
debug.socket(`Session hash seed is ${this.seed}`);
this.sessions = {};
this.hello_queue = {};
options = options || {};
this.port = options.port || 0;
this.address = options.address || '0.0.0.0';
this.socket = options.socket || null;
}
/**
* Open a socket and bind to it. If the port was set to `0` then the `port` property will be replaced with the bound port.
* @returns {Promise} Resolves without a result, or rejects with an error message.
*/
bind(){
return new Promise((res, rej) => {
if(!this.socket)
this.socket = dgram.createSocket('udp4');
const handleErrors = (err) => {
this.socket = null;
debug.udp(`Binding to ${this.address}:${this.port} failed with ${err}`);
rej(err);
};
this.socket.once('error', handleErrors);
debug.udp(`Attempting to bind to ${this.address}:${this.port}`);
this.socket.bind({
port: this.port,
address: this.address,
exclusive: true
}, () => {
this.socket.removeListener('error', handleErrors);
//this.socket.unref();
if(this.port && this.port !== this.socket.address().port)
throw Error('Could not bind to port '+this.port);
this.port = this.socket.address().port;
this.socket.on('message', (data, rinfo) => this.handleDatagram(data, rinfo));
debug.udp(`Binding to ${this.address}:${this.port} successful`);
res();
});
});
}
/**
* Close the socket, if bound or connected.
* @returns {Promise}
*/
close(){
this.removeAllListeners();
return new Promise(async (res, rej) => {
debug.udp(`Socket bound to ${this.address}:${this.port} now closing`);
Object.keys(this.sessions).forEach((id) => this.sessions[id].close());
await new Promise(res => setTimeout(res, 1));
if(this.socket){
this.socket.unref();
return this.socket.close(res);
}
res();
});
}
/**
* Send a message to another peer. The message will be received as a whole on the other end.
* @param {Buffer} message The message to be sent.
* @param {Number} port The port number to send to. The other end may use holepunhcing to go through the NAT.
* @param {String} address The IP address to send to. The other end may use holepunching to go through the NAT.
* @returns {Promise}
*/
send(message, port, address){
return new Promise((res, rej) => {
debug.udp(`Sending ${message.length} bytes to ${address}:${port}`);
this.socket.send(message, port, address, (err) => {
// TODO: What if a socket error?
if(err){
debug.udp(`Failed sending ${message.length} bytes to ${address}:${port}`);
return rej(err);
}
res();
});
});
}
/**
* Create a unique hash for this remote host address and port.
* @param {Object} rinfo Remote host information.
* @param {String} rinfo.address Remote host IP address.
* @param {Number} rinfo.port Remote host port number.
* @returns {Buffer}
*/
rinfoToHash(rinfo){
// TODO: SHA-256 might be an overkill, use something faster
return crypto.createHash('sha256').update(`${this.seed}:${rinfo.address}:${rinfo.port}`).digest();
}
/**
* Create a Hello datagram.
* @returns {Buffer}
*/
buildHelloDatagram(){
return Buffer.from([PROTOCOL_ID, DATAGRAM_CODES.RELIABLE_UDP_HELLO]);
}
/**
* Create a connection establish datagram
* @returns {Buffer}
*/
buildEstablishDatagram(){
return Buffer.from([PROTOCOL_ID, DATAGRAM_CODES.RELIABLE_UDP_ESTABLISH]);
}
/**
* Perform a DNS lookup.
* @param {String} hostname A hostname to convert to an IP address.
* @param {Object} [options] Options object (passed as a parameter to _dns.lookup_). Default options request an IPv4 address.
* @returns {Promise} An IP address for the host.
*/
async lookup(hostname, options){
return new Promise((res, rej) => {
debug.dns(`Resolving hostname ${hostname}`);
const guard = new Timeout(3000, () => rej('Lookup timeout'));
dns.lookup(hostname, options || {family: 4}, (err, address) => {
if(!guard.enterGate()){
debug.dns(`Response to ${hostname} came too late`);
return;
}
if(err){
debug.dns(`Could not resolve ${hostname}`);
return rej(err);
}
debug.dns(`Hostname ${hostname} is ${address}`);
res(address);
});
});
}
/**
* @description
* Execute the holepunching algorithm to create an address that another peer can connect to.
*
* @param {Object} [options] Pass additional options to the call.
* @param {String} [options.address=stun.l.google.com] A STUN server address to use.
* @param {Number} [options.port=19302] A STUN server port to use.
* @returns {Promise} Resolves with an array of pair [ip, port] as a result of holepunching, or rejects with an error message.
*/
discoverSelf(options){
return new Promise(async (res, rej) => {
try {
let stun_addr = await this.lookup('stun.l.google.com');
options = options || {};
const server = stun.createServer(this.socket);
const request = stun.createMessage(STUN_BINDING_REQUEST);
debug.stun(`STUN requesting a binding response`);
const guard = new Timeout(3000, () => rej('STUN binding request timeout'));
server.once('bindingResponse', (stunMsg) => {
if(!guard.enterGate()){
debug.stun(`Bidding response came back too late`);
return;
}
const results = {
ip: stunMsg.getAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS).value.address,
port: stunMsg.getAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS).value.port
};
debug.stun(`STUN Binding Response: ${JSON.stringify(stunMsg.getAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS).value)}`);
res([results.ip, results.port]);
setImmediate(() => server.close());
});
server.send(request, options.port || 19302, options.address || stun_addr);
}catch(err){
rej(err);
}
});
}
/**
* Attempt to establish a session with the peer. First sends a Hello packet, expects a Hello response, then sends an Establish packet and resolves the Promise.
* @param {String} address
* @param {Number} port
* @param {Number} [timeout=0] If a timeout is specified then the promise will reject after that time (miliseconds).
* @returns {Promise(StreamedUDPSession)} Resolved when the peer has answered to a hello. Otherwise rejected after a timeout.
*/
connect(address, port){
return new Promise(async (res, rej) => {
const guard = new Timeout(3000, () => rej(`Reliable connection to ${this.address}:${this.port} timeout`));
// 1. Send a hello packet, add host to a lightweight waiting list. (retry if needed)
// 2. When a hello is received from this host then send an establish packet.
// 3. Assume the connection has been established.
const rinfo = {address, port};
const hash = this.rinfoToHash(rinfo).toString('hex');
this.hello_queue[hash] = rinfo;
const hello = this.buildHelloDatagram();
debug.udp(hello.toString('hex'));
await this.send(hello, port, address);
if(!guard.isActive())return;
const self = this;
async function _check(id){
if(!guard.isActive())return;
if(id == hash){
guard.dismiss();
await self.send(self.buildEstablishDatagram(), port, address);
delete self.hello_queue[hash];
self.sessions[hash] = new Session(this.socket, address, port);
res(self.sessions[hash]);
}else{
self.once('expected-hello-recv', _check);
}
}
_check();
});
}
/**
* Handle incoming datagrams.
* @param {Buffer} datagram
* @param {Object} rinfo Remote host information.
* @param {String} rinfo.address Remote host IP address.
* @param {Number} rinfo.port Remote host port number.
*/
handleDatagram(datagram, rinfo){
const session_id = this.rinfoToHash(rinfo).toString('hex');
// TODO: Add firewall rules
debug.socket(`Got ${datagram.length} bytes from ${rinfo.address}:${rinfo.port} (session ${session_id}, ${this.sessions[session_id] ? 'existing' : 'unknown'}) = ${datagram.toString('hex')}`);
const protocol = datagram[0];
if(protocol != PROTOCOL_ID){
debug.socket(`Invalid protocol ${protocol}, ignoring`);
return;
}
const code = datagram[1];
switch(code){
case DATAGRAM_CODES.RELIABLE_UDP_HELLO:
// If unexpected hello then respond with a hello, otherwise make a session
if(!this.hello_queue[session_id]){
debug.socket(`Unexpected hello from ${rinfo.address}:${rinfo.port}, replying`);
this.send(this.buildHelloDatagram(), rinfo.port, rinfo.address);
this.hello_queue[session_id] = rinfo;
break;
}
this.emit('expected-hello-recv', session_id);
// continue to:
case DATAGRAM_CODES.RELIABLE_UDP_ESTABLISH:
// Remote end wants to establish a connection, allow only if helloed
if(!this.hello_queue[session_id]){
debug.socket(`Host ${rinfo.address}:${rinfo.port} attempted a connection without hello`);
break;
}
delete this.hello_queue[session_id];
this.sessions[session_id] = new Session(this.socket, rinfo.address, rinfo.port);
debug.socket(`Connection with ${rinfo.address}:${rinfo.port} (${session_id}) established`);
/**
* Emited when a connection has been established by another peer.
* @event StreamedUDPSession#new-peer
* @type {StreamedUDPSession}
*/
this.emit('new-peer', this.sessions[session_id]);
this.sessions[session_id].once('close', () => {
debug.socket(`Session ${session_id} from ${rinfo.address}:${rinfo.port} dropped`);
delete this.sessions[session_id];
});
break;
case DATAGRAM_CODES.RELIABLE_UDP_DATA:
if(!this.sessions[session_id]){
debug.socket(`Unexpected data received from ${rinfo.address}:${rinfo.port}`);
break;
}
this.sessions[session_id].onIncomingData(datagram.slice(2));
break;
case DATAGRAM_CODES.RELIABLE_UDP_RESEND_REQ:
if(!this.sessions[session_id]){
debug.socket(`Unexpected resend request received from ${rinfo.address}:${rinfo.port}`);
break;
}
if(datagram.length == 4){
const id = datagram.readUInt16BE(2);
this.sessions[session_id].onResendRequest(id);
}else{
debug.socket(`Invalid resend datagram from ${rinfo.address}:${rinfo.port}`);
}
break;
case DATAGRAM_CODES.RELIABLE_UDP_DATA_ACK:
if(!this.sessions[session_id]){
debug.socket(`Unexpected data ack received from ${rinfo.address}:${rinfo.port}`);
break;
}
if(datagram.length == 4){
const id = datagram.readUInt16BE(2);
this.sessions[session_id].onDataAck(id);
}else{
debug.socket(`Invalid data ack datagram from ${rinfo.address}:${rinfo.port}`);
}
break;
case DATAGRAM_CODES.RELIABLE_UDP_STATUS:
if(!this.sessions[session_id]){
debug.socket(`Unexpected status received from ${rinfo.address}:${rinfo.port}`);
break;
}
if(datagram.length == 4){
const id = datagram.readUInt16BE(2);
this.sessions[session_id].onStatus(id);
}else{
debug.socket(`Invalid status datagram from ${rinfo.address}:${rinfo.port}`);
}
break;
default:
debug.socket(`Unknown datagram code ${code}, datagram dropped`);
}
}
/**
* A generic method that allows sending data to any peer. Will connect if necessary.
* @param {Buffer} data
* @param {Number} port
* @param {String} address
* @returns {Promise}
*/
async sendData(data, port, address){
const hash = this.rinfoToHash({address, port}).toString('hex');
if(!this.sessions[hash])
await this.connect(address, port);
await this.sessions[hash].sendData(data);
}
}
module.exports = ReliableUDPSocket;