forked from peers/peerjs-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
430 lines (374 loc) · 11.2 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
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
var util = require('./util');
var bodyParser = require('body-parser');
var WebSocketServer = require('ws').Server;
var url = require('url');
var cors = require('cors');
var app = exports = module.exports = {};
/** Initialize WebSocket server. */
app._initializeWSS = function(server) {
var self = this;
if (this.mountpath instanceof Array) {
throw new Error("This app can only be mounted on a single path");
}
var path = this.mountpath;
var path = path + (path[path.length - 1] != '/' ? '/' : '') + 'peerjs';
// Create WebSocket server as well.
this._wss = new WebSocketServer({ path: path, server: server});
this._wss.on('connection', function(socket) {
var query = url.parse(socket.upgradeReq.url, true).query;
var id = query.id;
var token = query.token;
var room = query.room;
var key = query.key;
var ip = socket.upgradeReq.socket.remoteAddress;
if (!id || !token || !key) {
socket.send(JSON.stringify({ type: 'ERROR', payload: { msg: 'No id, token, or key supplied to websocket server' } }));
socket.close();
return;
}
if (!self._clients[key] || !self._clients[key][id]) {
self._checkKey(key, ip, room, function(err) {
if (!err) {
if (!self._clients[key][id]) {
self._clients[key][id] = { token: token, ip: ip, room: room };
self._ips[ip]++;
self._room_members[room][id] = id;
socket.send(JSON.stringify({ type: 'OPEN' }));
}
self._configureWS(socket, key, id, token);
} else {
socket.send(JSON.stringify({ type: 'ERROR', payload: { msg: err } }));
}
});
} else {
self._configureWS(socket, key, id, token);
}
});
};
app._configureWS = function(socket, key, id, token, room) {
var self = this;
var client = this._clients[key][id];
if (token === client.token) {
// res 'close' event will delete client.res for us
client.socket = socket;
// Client already exists
if (client.res) {
client.res.end();
}
} else {
// ID-taken, invalid token
socket.send(JSON.stringify({ type: 'ID-TAKEN', payload: { msg: 'ID is taken' } }));
socket.close();
return;
}
this._processOutstanding(key, id);
// Cleanup after a socket closes.
socket.on('close', function() {
self._log('Socket closed:', id);
if (client.socket == socket) {
self._removePeer(key, id);
}
});
// Handle messages from peers.
socket.on('message', function(data) {
try {
var message = JSON.parse(data);
if (['LEAVE', 'CANDIDATE', 'OFFER', 'ANSWER'].indexOf(message.type) !== -1) {
self._handleTransmission(key, {
type: message.type,
src: id,
dst: message.dst,
payload: message.payload
});
} else {
util.prettyError('Message unrecognized');
}
} catch(e) {
self._log('Invalid message', data);
throw e;
}
});
// We're going to emit here, because for XHR we don't *know* when someone
// disconnects.
this.emit('connection', id);
};
app._checkAllowsDiscovery = function(key, cb) {
cb(this._options.allow_discovery);
};
app._checkKey = function(key, ip, room, cb) {
if (key == this._options.key) {
if (!this._clients[key]) {
this._clients[key] = {};
}
if (!this._outstanding[key]) {
this._outstanding[key] = {};
}
if (!this._ips[ip]) {
this._ips[ip] = 0;
}
if (!this._room_members[room]) {
this._room_members[room] = {};
}
// Check concurrent limit
if (Object.keys(this._clients[key]).length >= this._options.concurrent_limit) {
cb('Server has reached its concurrent user limit');
return;
}
if (this._ips[ip] >= this._options.ip_limit) {
cb(ip + ' has reached its concurrent user limit');
return;
}
cb(null);
} else {
cb('Invalid key provided');
}
};
/** Initialize HTTP server routes. */
app._initializeHTTP = function() {
var self = this;
this.use(cors());
this.get('/', function(req, res, next) {
res.send(require('../app.json'));
});
// Retrieve guaranteed random ID.
this.get('/:key/id', function(req, res, next) {
res.contentType = 'text/html';
res.send(self._generateClientId(req.params.key));
});
// Server sets up HTTP streaming when you get post an ID.
this.post('/:key/:id/:token/:room/id', function(req, res, next) {
var id = req.params.id;
var token = req.params.token;
var key = req.params.key;
var room = req.params.room;
var ip = req.connection.remoteAddress;
if (!self._clients[key] || !self._clients[key][id]) {
self._checkKey(key, ip, room, function(err) {
if (!err && !self._clients[key][id]) {
self._clients[key][id] = { token: token, ip: ip, room:room };
self._ips[ip]++;
self._room_members[room][id] = id;
self._startStreaming(res, key, id, token, true);
} else {
res.send(JSON.stringify({ type: 'HTTP-ERROR' }));
}
});
} else {
self._startStreaming(res, key, id, token);
}
});
// Get a list of all peers for a key, enabled by the `allowDiscovery` flag.
this.get('/:key/peers', function(req, res, next) {
var key = req.params.key;
if (self._clients[key]) {
self._checkAllowsDiscovery(key, function(isAllowed) {
if (isAllowed) {
res.send(Object.keys(self._clients[key]));
} else {
res.sendStatus(401);
}
});
} else {
res.sendStatus(404);
}
});
var handle = function(req, res, next) {
var key = req.params.key;
var id = req.params.id;
var client;
if (!self._clients[key] || !(client = self._clients[key][id])) {
if (req.params.retry) {
res.sendStatus(401);
} else {
// Retry this request
req.params.retry = true;
setTimeout(handle, 25, req, res);
return;
}
}
// Auth the req
if (req.params.token !== client.token) {
res.sendStatus(401);
return;
} else {
self._handleTransmission(key, {
type: req.body.type,
src: id,
dst: req.body.dst,
payload: req.body.payload
});
res.sendStatus(200);
}
};
var jsonParser = bodyParser.json();
this.post('/:key/:id/:token/offer', jsonParser, handle);
this.post('/:key/:id/:token/candidate', jsonParser, handle);
this.post('/:key/:id/:token/answer', jsonParser, handle);
this.post('/:key/:id/:token/leave', jsonParser, handle);
};
/** Saves a streaming response and takes care of timeouts and headers. */
app._startStreaming = function(res, key, id, token, open) {
var self = this;
res.writeHead(200, {'Content-Type': 'application/octet-stream'});
var pad = '00';
for (var i = 0; i < 10; i++) {
pad += pad;
}
res.write(pad + '\n');
if (open) {
res.write(JSON.stringify({ type: 'OPEN' }) + '\n');
}
var client = this._clients[key][id];
if (token === client.token) {
// Client already exists
res.on('close', function() {
if (client.res === res) {
if (!client.socket) {
// No new request yet, peer dead
self._removePeer(key, id);
return;
}
delete client.res;
}
});
client.res = res;
this._processOutstanding(key, id);
} else {
// ID-taken, invalid token
res.end(JSON.stringify({ type: 'HTTP-ERROR' }));
}
};
app._pruneOutstanding = function() {
var keys = Object.keys(this._outstanding);
for (var k = 0, kk = keys.length; k < kk; k += 1) {
var key = keys[k];
var dsts = Object.keys(this._outstanding[key]);
for (var i = 0, ii = dsts.length; i < ii; i += 1) {
var offers = this._outstanding[key][dsts[i]];
var seen = {};
for (var j = 0, jj = offers.length; j < jj; j += 1) {
var message = offers[j];
if (!seen[message.src]) {
this._handleTransmission(key, { type: 'EXPIRE', src: message.dst, dst: message.src });
seen[message.src] = true;
}
}
}
this._outstanding[key] = {};
}
};
/** Cleanup */
app._setCleanupIntervals = function() {
var self = this;
// Clean up ips every 10 minutes
setInterval(function() {
var keys = Object.keys(self._ips);
for (var i = 0, ii = keys.length; i < ii; i += 1) {
var key = keys[i];
if (self._ips[key] === 0) {
delete self._ips[key];
}
}
}, 600000);
// Clean up outstanding messages every 5 seconds
setInterval(function() {
self._pruneOutstanding();
}, 5000);
};
/** Process outstanding peer offers. */
app._processOutstanding = function(key, id) {
var offers = this._outstanding[key][id];
if (!offers) {
return;
}
for (var j = 0, jj = offers.length; j < jj; j += 1) {
this._handleTransmission(key, offers[j]);
}
delete this._outstanding[key][id];
};
app._removePeer = function(key, id) {
if (this._clients[key] && this._clients[key][id]) {
var client = this._clients[key][id];
var room = client.room;
this._ips[this._clients[key][id].ip]--;
delete this._clients[key][id];
delete this._room_members[client.room][id];
// send to members
var members = Object.keys(this._room_members[room]);
for (var k = 0, kk = members.length; k < kk; k += 1) {
var member = members[k];
this._handleTransmission(key, {
type: "LEAVE",
src: id,
dst: member
});
}
console.log(this._clients);
console.log(this._ips);
console.log(this._room_members);
this.emit('disconnect', id);
}
};
/** Handles passing on a message. */
app._handleTransmission = function(key, message) {
var type = message.type;
var src = message.src;
var dst = message.dst;
var data = JSON.stringify(message);
var destination = this._clients[key][dst];
// User is connected!
if (destination) {
try {
this._log(type, 'from', src, 'to', dst);
if (destination.socket) {
destination.socket.send(data);
} else if (destination.res) {
data += '\n';
destination.res.write(data);
} else {
// Neither socket no res available. Peer dead?
throw "Peer dead";
}
} catch (e) {
// This happens when a peer disconnects without closing connections and
// the associated WebSocket has not closed.
// Tell other side to stop trying.
this._removePeer(key, dst);
this._handleTransmission(key, {
type: 'LEAVE',
src: dst,
dst: src
});
}
} else {
// Wait for this client to connect/reconnect (XHR) for important
// messages.
if (type !== 'LEAVE' && type !== 'EXPIRE' && dst) {
var self = this;
if (!this._outstanding[key][dst]) {
this._outstanding[key][dst] = [];
}
this._outstanding[key][dst].push(message);
} else if (type === 'LEAVE' && !dst) {
this._removePeer(key, src);
} else {
// Unavailable destination specified with message LEAVE or EXPIRE
// Ignore
}
}
};
app._generateClientId = function(key) {
var clientId = util.randomId();
if (!this._clients[key]) {
return clientId;
}
while (!!this._clients[key][clientId]) {
clientId = util.randomId();
}
return clientId;
};
app._log = function() {
if (this._options.debug) {
console.log.apply(console, arguments);
}
};