This repository was archived by the owner on Sep 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathconnector.js
More file actions
458 lines (397 loc) · 11.7 KB
/
Copy pathconnector.js
File metadata and controls
458 lines (397 loc) · 11.7 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
var logger = require('pomelo-logger').getLogger('pomelo', __filename);
var taskManager = require('../common/manager/taskManager');
var pomelo = require('../pomelo');
var rsa = require("node-bignumber");
var events = require('../util/events');
var utils = require('../util/utils');
module.exports = function(app, opts) {
return new Component(app, opts);
};
/**
* Connector component. Receive client requests and attach session with socket.
*
* @param {Object} app current application context
* @param {Object} opts attach parameters
* opts.connector {Object} provides low level network and protocol details implementation between server and clients.
*/
var Component = function(app, opts) {
opts = opts || {};
this.app = app;
this.connector = getConnector(app, opts);
this.encode = opts.encode;
this.decode = opts.decode;
this.useCrypto = opts.useCrypto;
this.useHostFilter = opts.useHostFilter;
this.useAsyncCoder = opts.useAsyncCoder;
this.blacklistFun = opts.blacklistFun;
this.keys = {};
this.blacklist = [];
if (opts.useDict) {
app.load(pomelo.dictionary, app.get('dictionaryConfig'));
}
if (opts.useProtobuf) {
app.load(pomelo.protobuf, app.get('protobufConfig'));
}
// component dependencies
this.server = null;
this.session = null;
this.connection = null;
};
var pro = Component.prototype;
pro.name = '__connector__';
pro.start = function(cb) {
this.server = this.app.components.__server__;
this.session = this.app.components.__session__;
this.connection = this.app.components.__connection__;
// check component dependencies
if (!this.server) {
process.nextTick(function() {
utils.invokeCallback(cb, new Error('fail to start connector component for no server component loaded'));
});
return;
}
if (!this.session) {
process.nextTick(function() {
utils.invokeCallback(cb, new Error('fail to start connector component for no session component loaded'));
});
return;
}
process.nextTick(cb);
};
pro.afterStart = function(cb) {
this.connector.start(cb);
this.connector.on('connection', hostFilter.bind(this, bindEvents));
};
pro.stop = function(force, cb) {
if (this.connector) {
this.connector.stop(force, cb);
this.connector = null;
return;
} else {
process.nextTick(cb);
}
};
pro.send = function(reqId, route, msg, recvs, opts, cb) {
logger.debug('[%s] send message reqId: %s, route: %s, msg: %j, receivers: %j, opts: %j', this.app.serverId, reqId, route, msg, recvs, opts);
if (this.useAsyncCoder) {
return this.sendAsync(reqId, route, msg, recvs, opts, cb);
}
var emsg = msg;
if (this.encode) {
// use costumized encode
emsg = this.encode.call(this, reqId, route, msg);
} else if (this.connector.encode) {
// use connector default encode
emsg = this.connector.encode(reqId, route, msg);
}
this.doSend(reqId, route, emsg, recvs, opts, cb);
};
pro.sendAsync = function(reqId, route, msg, recvs, opts, cb) {
var emsg = msg;
var self = this;
if (this.encode) {
// use costumized encode
this.encode(reqId, route, msg, function(err, encodeMsg) {
if (err) {
return cb(err);
}
emsg = encodeMsg;
self.doSend(reqId, route, emsg, recvs, opts, cb);
});
} else if (this.connector.encode) {
// use connector default encode
this.connector.encode(reqId, route, msg, function(err, encodeMsg) {
if (err) {
return cb(err);
}
emsg = encodeMsg;
self.doSend(reqId, route, emsg, recvs, opts, cb);
});
}
}
pro.doSend = function(reqId, route, emsg, recvs, opts, cb) {
if (!emsg) {
process.nextTick(function() {
return cb && cb(new Error('fail to send message for encode result is empty.'));
});
}
this.app.components.__pushScheduler__.schedule(reqId, route, emsg,
recvs, opts, cb);
}
pro.setPubKey = function(id, key) {
var pubKey = new rsa.Key();
pubKey.n = new rsa.BigInteger(key.rsa_n, 16);
pubKey.e = key.rsa_e;
this.keys[id] = pubKey;
};
pro.getPubKey = function(id) {
return this.keys[id];
};
var getConnector = function(app, opts) {
var connector = opts.connector;
if (!connector) {
return getDefaultConnector(app, opts);
}
if (typeof connector !== 'function') {
return connector;
}
var curServer = app.getCurServer();
var host = curServer.clientHost || curServer.host;
return connector(curServer.clientPort, host, opts);
};
var getDefaultConnector = function(app, opts) {
var DefaultConnector = require('../connectors/sioconnector');
var curServer = app.getCurServer();
var host = curServer.clientHost || curServer.host;
return new DefaultConnector(curServer.clientPort, host, opts);
};
var hostFilter = function(cb, socket) {
if(!this.useHostFilter) {
return cb(this, socket);
}
var ip = socket.remoteAddress.ip;
var check = function(list) {
for (var address in list) {
var exp = new RegExp(list[address]);
if (exp.test(ip)) {
socket.disconnect();
return true;
}
}
return false;
};
// dynamical check
if (this.blacklist.length !== 0 && !!check(this.blacklist)) {
return;
}
// static check
if (!!this.blacklistFun && typeof this.blacklistFun === 'function') {
var self = this;
self.blacklistFun(function(err, list) {
if (!!err) {
logger.error('connector blacklist error: %j', err.stack);
utils.invokeCallback(cb, self, socket);
return;
}
if (!Array.isArray(list)) {
logger.error('connector blacklist is not array: %j', list);
utils.invokeCallback(cb, self, socket);
return;
}
if (!!check(list)) {
return;
} else {
utils.invokeCallback(cb, self, socket);
return;
}
});
} else {
utils.invokeCallback(cb, this, socket);
}
};
var bindEvents = function(self, socket) {
var curServer = self.app.getCurServer();
var maxConnections = curServer['max-connections'];
if (self.connection && maxConnections) {
self.connection.increaseConnectionCount();
var statisticInfo = self.connection.getStatisticsInfo();
if (statisticInfo.totalConnCount > maxConnections) {
logger.warn('the server %s has reached the max connections %s', curServer.id, maxConnections);
socket.disconnect();
return;
}
}
//create session for connection
var session = getSession(self, socket);
var closed = false;
socket.on('disconnect', function() {
if (closed) {
return;
}
closed = true;
if (self.connection) {
self.connection.decreaseConnectionCount(session.uid);
}
});
socket.on('error', function() {
if (closed) {
return;
}
closed = true;
if (self.connection) {
self.connection.decreaseConnectionCount(session.uid);
}
});
// new message
socket.on('message', function(msg) {
var dmsg = msg;
if (self.useAsyncCoder) {
return handleMessageAsync(self, msg, session, socket);
}
if (self.decode) {
dmsg = self.decode(msg, session);
} else if (self.connector.decode) {
dmsg = self.connector.decode(msg, socket);
}
if (!dmsg) {
// discard invalid message
return;
}
// use rsa crypto
if (self.useCrypto) {
var verified = verifyMessage(self, session, dmsg);
if (!verified) {
logger.error('fail to verify the data received from client.');
return;
}
}
handleMessage(self, session, dmsg);
}); //on message end
};
var handleMessageAsync = function(self, msg, session, socket) {
if (self.decode) {
self.decode(msg, session, function(err, dmsg) {
if (err) {
logger.error('fail to decode message from client %s .', err.stack);
return;
}
doHandleMessage(self, dmsg, session);
});
} else if (self.connector.decode) {
self.connector.decode(msg, socket, function(err, dmsg) {
if (err) {
logger.error('fail to decode message from client %s .', err.stack);
return;
}
doHandleMessage(self, dmsg, session);
});
}
}
var doHandleMessage = function(self, dmsg, session) {
if (!dmsg) {
// discard invalid message
return;
}
// use rsa crypto
if (self.useCrypto) {
var verified = verifyMessage(self, session, dmsg);
if (!verified) {
logger.error('fail to verify the data received from client.');
return;
}
}
handleMessage(self, session, dmsg);
}
/**
* get session for current connection
*/
var getSession = function(self, socket) {
var app = self.app,
sid = socket.id;
var session = self.session.get(sid);
if (session) {
return session;
}
session = self.session.create(sid, app.getServerId(), socket);
logger.debug('[%s] getSession session is created with session id: %s', app.getServerId(), sid);
// bind events for session
socket.on('disconnect', session.closed.bind(session));
socket.on('error', session.closed.bind(session));
session.on('closed', onSessionClose.bind(null, app));
session.on('bind', function(uid) {
logger.debug('session on [%s] bind with uid: %s', self.app.serverId, uid);
// update connection statistics if necessary
if (self.connection) {
self.connection.addLoginedUser(uid, {
loginTime: Date.now(),
uid: uid,
address: socket.remoteAddress.ip + ':' + socket.remoteAddress.port
});
}
self.app.event.emit(events.BIND_SESSION, session);
});
session.on('unbind', function(uid) {
if (self.connection) {
self.connection.removeLoginedUser(uid);
}
self.app.event.emit(events.UNBIND_SESSION, session);
});
return session;
};
var onSessionClose = function(app, session, reason) {
taskManager.closeQueue(session.id, true);
app.event.emit(events.CLOSE_SESSION, session);
};
var handleMessage = function(self, session, msg) {
logger.debug('[%s] handleMessage session id: %s, msg: %j', self.app.serverId, session.id, msg);
var type = checkServerType(msg.route);
if (!type) {
logger.error('invalid route string. route : %j', msg.route);
return;
}
self.server.globalHandle(msg, session.toFrontendSession(), function(err, resp, opts) {
if (resp && !msg.id) {
logger.warn('try to response to a notify: %j', msg.route);
return;
}
if (!msg.id && !resp) return;
if (!resp) resp = {};
if (!!err && !resp.code) {
resp.code = 500;
}
opts = {
type: 'response',
userOptions: opts || {}
};
// for compatiablity
opts.isResponse = true;
self.send(msg.id, msg.route, resp, [session.id], opts,
function() {});
});
};
/**
* Get server type form request message.
*/
var checkServerType = function(route) {
if (!route) {
return null;
}
var idx = route.indexOf('.');
if (idx < 0) {
return null;
}
return route.substring(0, idx);
};
var verifyMessage = function(self, session, msg) {
var sig = msg.body.__crypto__;
if (!sig) {
logger.error('receive data from client has no signature [%s]', self.app.serverId);
return false;
}
var pubKey;
if (!session) {
logger.error('could not find session.');
return false;
}
if (!session.get('pubKey')) {
pubKey = self.getPubKey(session.id);
if (!!pubKey) {
delete self.keys[session.id];
session.set('pubKey', pubKey);
} else {
logger.error('could not get public key, session id is %s', session.id);
return false;
}
} else {
pubKey = session.get('pubKey');
}
if (!pubKey.n || !pubKey.e) {
logger.error('could not verify message without public key [%s]', self.app.serverId);
return false;
}
delete msg.body.__crypto__;
var message = JSON.stringify(msg.body);
if (utils.hasChineseChar(message))
message = utils.unicodeToUtf8(message);
return pubKey.verifyString(message, sig);
};