-
Notifications
You must be signed in to change notification settings - Fork 27
/
server.js
290 lines (247 loc) · 7.69 KB
/
server.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
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
'use strict';
var dgram = require('dgram');
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var DtlsSocket = require('./socket');
var mbed = require('./build/Release/node_mbed_dtls');
const APPLICATION_DATA_CONTENT_TYPE = 23;
const IP_CHANGE_CONTENT_TYPE = 254;
class DtlsServer extends EventEmitter {
constructor(options) {
super();
if(!options) {
throw "Parameter options is not set";
}
if (options.key == undefined) {
throw "Parameter 'key' is not set";
}
if (options.identityPskCallback == undefined) {
throw "Parameter 'identityPskCallback' is not set";
}
this.options = Object.assign({
sendClose: true
}, options);
this.sockets = {};
this.dgramSocket = dgram.createSocket('udp4');
this._onMessage = this._onMessage.bind(this);
this.listening = false;
this.dgramSocket.on('message', this._onMessage);
this.dgramSocket.once('listening', () => {
this.listening = true;
this.emit('listening');
});
this.dgramSocket.once('error', err => {
this.emit('error', err);
this._closeSocket();
});
this.dgramSocket.once('close', () => {
this._socketClosed();
});
let key = Buffer.isBuffer(options.key) ? options.key : fs.readFileSync(options.key);
// likely a PEM encoded key, add null terminating byte
// 0x2d = '-'
if (key[0] === 0x2d && key[key.length - 1] !== 0) {
key = Buffer.concat([key, new Buffer([0])]);
}
this.mbedServer = new mbed.DtlsServer(key, options.identityPskCallback, options.debug);
if (options.handshakeTimeoutMin) {
this.mbedServer.handshakeTimeoutMin = options.handshakeTimeoutMin;
}
}
listen(port, hostname, callback) {
this.dgramSocket.bind(port, hostname, callback);
}
close(callback) {
if (callback) {
this.once('close', callback);
}
this._closing = true;
this._endSockets();
}
address() {
return this.dgramSocket.address();
}
getConnections(callback) {
var numConnections = Object.keys(this.sockets).filter(skey => {
return this.sockets[skey] && this.sockets[skey].connected;
}).length;
process.nextTick(() => callback(numConnections));
}
resumeSocket(rinfo, session) {
const key = `${rinfo.address}:${rinfo.port}`;
let client = this.sockets[key];
if (client) {
return false;
}
this.sockets[key] = client = this._createSocket(rinfo, key, true);
if (client.resumeSession(session)) {
this.emit('secureConnection', client, session);
return true;
}
return false;
}
_debug() {
if (this.options.debug) {
console.log(...arguments);
}
}
_handleIpChange(msg, key, rinfo, deviceId) {
const lookedUp = this.emit('lookupKey', deviceId, (err, oldRinfo) => {
if (!err && oldRinfo) {
// if the IP hasn't actually changed, handle normally
if (rinfo.address === oldRinfo.address &&
rinfo.port === oldRinfo.port) {
this._debug(`ignoring ip change because address did not change ip=${key}, deviceID=${deviceId}`);
this._onMessage(msg, rinfo);
return;
}
this._onMessage(msg, oldRinfo, (client, received) => {
// if the message went through OK
if (received) {
const oldKey = `${oldRinfo.address}:${oldRinfo.port}`;
this._debug(`message successfully received, changing ip address fromip=${oldKey}, toip=${key}, deviceID=${deviceId}`);
// change IP
client.remoteAddress = rinfo.address;
client.remotePort = rinfo.port;
// move in lookup table
this.sockets[key] = client;
delete this.sockets[oldKey];
// tell the world
client.emit('ipChanged', oldRinfo);
}
});
}
});
return lookedUp;
}
_attemptResume(client, msg, key, cb) {
const lcb = cb || (() => {});
const called = this.emit('resumeSession', key, client, (err, session) => {
if (!err && session) {
const resumed = client.resumeSession(session);
if (resumed) {
client.cork();
const received = client.receive(msg);
// callback before secureConnection so
// IP can be changed
lcb(client, received);
if (received) {
this.emit('secureConnection', client, session);
}
client.uncork();
return;
}
}
client.receive(msg);
lcb(null, false);
});
// if somebody was listening, session will attempt to be resumed
// do not process with receive until resume finishes
return called;
}
_onMessage(msg, rinfo, cb) {
const key = `${rinfo.address}:${rinfo.port}`;
// special IP changed content type
if (msg.length > 0 && msg[0] === IP_CHANGE_CONTENT_TYPE) {
const idLen = msg[msg.length - 1];
const idStartIndex = msg.length - idLen - 1;
const deviceId = msg.slice(idStartIndex, idStartIndex + idLen).toString('hex').toLowerCase();
// slice off id and length, return content type to ApplicationData
msg = msg.slice(0, idStartIndex);
msg[0] = APPLICATION_DATA_CONTENT_TYPE;
this._debug(`received ip change ip=${key}, deviceID=${deviceId}`);
if (this._handleIpChange(msg, key, rinfo, deviceId)) {
return;
}
}
let client = this.sockets[key];
if (!client) {
this.sockets[key] = client = this._createSocket(rinfo, key);
if (msg.length > 0 && msg[0] === APPLICATION_DATA_CONTENT_TYPE) {
if (this._attemptResume(client, msg, key, cb)) {
return;
}
}
}
if (cb) {
// we cork because we want the callback to happen
// before the implications of the message do
client.cork();
const received = client.receive(msg);
cb(client, received);
client.uncork();
} else {
client.receive(msg);
}
}
_createSocket(rinfo, key, selfRestored) {
var client = new DtlsSocket(this, rinfo.address, rinfo.port);
client.sendClose = this.options.sendClose;
client.selfRestored = selfRestored;
this._attachToSocket(client, key);
return client;
}
_attachToSocket(client, key) {
client.once('error', (code, err) => {
delete this.sockets[key];
if (!client.connected) {
this.emit('clientError', err, client);
}
});
client.once('close', () => {
delete this.sockets[key];
client = null;
if (this._closing && Object.keys(this.sockets).length === 0) {
this._closeSocket();
}
});
client.once('reconnect', socket => {
// treat like a brand new connection
socket.reset();
this._attachToSocket(socket, key);
this.sockets[key] = socket;
});
client.once('secureConnect', () => {
this.emit('secureConnection', client);
});
this.emit('connection', client);
}
_endSockets() {
if (this.dgramSocket) {
this.dgramSocket.removeListener('message', this._onMessage);
}
const sockets = Object.keys(this.sockets);
sockets.forEach(skey => {
const s = this.sockets[skey];
if (s) {
s.end();
}
});
if (sockets.length === 0) {
this._closeSocket();
}
}
_socketClosed() {
this.listening = false;
if (this.dgramSocket) {
this.dgramSocket.removeListener('message', this._onMessage);
}
this.dgramSocket = null;
this._endSockets();
this.sockets = {};
this.emit('close');
this.removeAllListeners();
}
_closeSocket() {
if (!this.listening) {
process.nextTick(() => {
this._socketClosed();
});
return;
}
if (this.dgramSocket) {
this.dgramSocket.close();
}
}
}
module.exports = DtlsServer;