-
Notifications
You must be signed in to change notification settings - Fork 4
/
appnet.link-server-v2.js
2743 lines (2278 loc) · 134 KB
/
appnet.link-server-v2.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
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// AppNet.Link name-server V2 implementation based SecureWebsocket and NaclCert, that works with appnet.link name-client
// Copyright (c) 2014-present Tom Zhou<[email protected]>
//
'use strict';
var debug = require('debug')('appnet.link.srv.v2');
// AppNet.link module
var AppNet = require('appnet.link').V2;
// Session establish protocol
var SEP = AppNet.SEP;
// eventEmitter
var eventEmitter = require('events'),
util = require('util'),
url = require('url'),
http = require('http'),
https = require('https'),
httpp = require('httpp'),
httpps = require('httpps'),
crypto = require('crypto'),
Connect = require('connect'),
connect_httpp = require('connect-httpp'),
UDT = require('udt');
// security hash
// SIPKEY can be any user defined 4 integers
var SIPHASH = require('siphash'),
SIPKEY = [0x33336666, 0x33338888, 0x88889999, 0x11116666]; // magic key
// MSGPACK library
var MSGPACK = require('msgpack-js');
// p2p stream websocket library
///var WebSocket = require('wspp');
///var WebSocketServer = WebSocket.Server;
// secure websocket library
var SecureWebSocket = require('node-sws');
var SecureWebSocketServer = SecureWebSocket.Server;
var Naclcert = SecureWebSocket.Naclcert;
// httpp-proxy library
var httppProxy = require('httpp-proxy').httppproxy;
// UUID generator
var UUID = require('uuid');
// SDP model
var Sdp = require('./sdp');
// STUN model
var Stun = require('./stun');
// TURN model
var Turn = require('./turn');
// vURL model
var vurl = require('./vurl');
var vURL = new vurl(); // memory store by now TBD... memory DB
// Peer service model
var peerservice = require('./peerservice');
var peerService = new peerservice(); // memory store by now TBD... memory DB
// SSL binary wrap
var SSL = require('./ssl');
// GeoIP model
var geoIP = require('geoip-lite');
// Debug level
// 1: display error, proxy entry
// 2: display req/res headers/statusCode
var Debug = 0;
// name-server pair: primary/alternate listen on UDP port 51686/51868 in default
// turn-server pair: proxy/agent server
// - endpoints : {dn: domain name, ipaddr: name-server hostname or IP, ports: [primary,alternative], turn: [proxy,agent], option: {mbw:xxx, ...}}
// - endpoints.dn : server's domain name, it's needed for TURN session
// - endpoints.turn : turn proxy/agent ports
// - endpoints.option: default user-specific features,like mbw - maxim bandwidth, etc
// -
// - seccerts: {
// // SSL certs
// sslcerts: {
// ca: {key: xxx, cert: xxx, cont: xxx},
// ns: {key: xxx, cert: yyy},
// as: {key: xxx, cert: yyy},
// ps: {key: xxx, cert: yyy, subdn:{'subdomain': {key:x, cert: x}}}} https/httpps SSL certs
// },
// // NACL certs
// naclcerts: {
// ca: {key: xxx, cert: xxx},
// ns: {key: xxx, cert: yyy},
// as: {key: xxx, cert: yyy},
// ps: {key: xxx, cert: yyy} secure websocket NACL certs
// }
// }
var nmSrv = exports = module.exports = function(endpoints, seccerts){
if (!(this instanceof nmSrv)) return new nmSrv(endpoints, seccerts);
var self = this;
// super constructor
eventEmitter.call(self);
// at least two ports to listen
self.dn = endpoints.dn || '51dese.com';
self.ipaddr = endpoints.ipaddr || '0.0.0.0';
self.ports = endpoints.ports || [51686, 51868];
// check on secure certs /////////////////////////////
seccerts = seccerts || {};
var sslcerts = (seccerts && seccerts.sslcerts) || {};
var naclcerts = (seccerts && seccerts.naclcerts) || {};
// SSL certs
self.sslcerts = sslcerts || {};
self.sslcerts.ns = self.sslcerts.ns || false;
self.sslcerts.as = self.sslcerts.as || false;
self.sslcerts.ps = self.sslcerts.ps || false;
// ssl CA cert/key
self.sslcerts.ca = self.sslcerts.ca || false;
// NACL certs
self.naclcerts = naclcerts || {};
self.naclcerts.ns = self.naclcerts.ns || false;
self.naclcerts.as = self.naclcerts.as || false;
self.naclcerts.ps = self.naclcerts.ps || false;
// NACL CA cert/key
self.naclcerts.ca = self.naclcerts.ca || {};
self.naclcerts.ca.cert = self.naclcerts.ca.cert || Naclcert.rootCACert;
//////////////////////////////////////////////////////
// default user-specific features
self.option = endpoints.option || {};
// server obj cache
self.srvs = {};
// clients connection cache
self.conn = {}; // ['clnt2srv'] = client connection
// turn server obj cache
self.turnPorts = endpoints.turn;
self.turnSrvs = {}; // proxy/agent server
self.turnConn = {}; // ['clnt2agentsrv'/''clnt2proxysrv''] = client connection
self.turnProxyCache = {}; // proxy cache to record vurl to httpp-proxy map. TBD... with DB
self.trunProxyHistory = {}; // proxy history to record user connection info to vurl map. TBD... with DB
// - key: user connection host:vurl or host:port:vurl in case security mode 2
// - val: {
// timestamp: // timestamp of connection
// state: , // 0: fail, 1: pass, -1: reject with timeout,
// trys: , // re-try times before pass
// maxTrys: , // maxim re-trys. default 6 times
// timeOut: // reject timeout. default 6s
// }
// wrap socket.send method
function sendOpcMsg(socket, opc_msg, fn){
try {
if (socket && socket.send) {
// V2 will use msgpack
socket.send(MSGPACK.encode(opc_msg), {binary: true, mask: false}, function(err){
if (err) {
console.log(err+',sendOpcMsg failed');
if (fn) fn(err+',sendOpcMsg failed');
} else {
if (fn) fn(null);
}
});
} else {
console.log('invalid socket,sendOpcMsg failed immediately');
if (fn) fn('invalid socket,sendOpcMsg failed immediately');
}
} catch (e) {
console.log(e+',sendOpcMsg failed immediately');
if (fn) fn(e+',sendOpcMsg failed immediately');
}
}
// on connection process
function onConnection(client) {
var sk, ck; // key for server/client on public ip/port
var peerclnt; // the connection obj which the peer come from
var mineclnt; // the connection obj which the client come from
if (Debug) console.log('new connection');
// initialize offer message count per client
// every time, server send one offer message, increase it by one
client.offerMsgcnt = 0;
// onMessage handler
client.on('message', function(message, flags){
// !!! catch any exceptions and ignore it
try {
var data = (flags.binary) ? MSGPACK.decode(message) : JSON.parse(message);
if (Debug) console.log('nmsrv:new message:'+JSON.stringify(data));
// check if opc is valid
if ('number' === typeof data.opc) {
switch (data.opc) {
// offer/answer opc -> /////////////////////////////////////////////
case SEP.SEP_OPC_SDP_OFFER:
// 1.
// check offer credit by user info
// 1.1
// notes: only support 51dese.com as domain at present !!!
if (data.offer.domain != '51dese.com' && data.offer.domain != 'www.51dese.com') {
console.log('invalid domain, please use 51dese.com by now');
data.opc = SEP.SEP_OPC_SDP_ANSWER;
data.answer = {};
data.answer.ready = false;
data.answer.error = 'invalid domain, please use 51dese.com by now';
// 1.1.1
// send back answer message, then close client and agent client in case have
sendOpcMsg(client, data, function(err){
if (err) console.log(err+'sendOpcMsg failed');
setTimeout(function(){
if (client && client.close) client.close();
}, 2000); // 2s timeout
});
// 1.1.1.1
// emit event
self.emit('NS.SEP.SEP_OPC_SDP_OFFER', {client: client, data: data});
break;
}
// 1.2
// check if usrkey is existing
// TBD...
//Sdp.testUser({domain: data.offer.domain, usrkey: data.offer.usrkey}, function(err, yes){
//});
// 2.
// record SDP session
var sesn = {};
//sesn = data.offer;
for (var k in data.offer) {
sesn[k] = data.offer[k];
}
// 2.1
// fill session info saw by server
sesn.clntpublicIP = client.remoteAddress;
sesn.clntpublicPort = client.remotePort;
sesn.srvlocalIP = client.address().address;
sesn.srvlocalPort = client.address().port;
sesn.srvpublicDN = self.dn;
sesn.sid = UUID.v4();
// 2.2
// query client's geoIP
sesn.clntgeoip = JSON.stringify(geoIP.lookup(client.remoteAddress));
if (Debug) console.log('new name-client GeoIP:'+sesn.clntgeoip);
// 2.3
// persistent session info
var sdp = new Sdp(sesn);
if (Debug) console.log('new SDP session:'+JSON.stringify(sdp));
sdp.saveOupdate(function(err, sdp){
// 3.
// send back SDP answer
data.opc = SEP.SEP_OPC_SDP_ANSWER;
data.answer = {};
if (err || !sdp) {
console.log('new SDP session failed:'+err);
// send back fake SDP session as answer
data.answer = {};
data.answer.state = SEP.SEP_OPC_STATE_FAIL;
// close socket after 2s
sendOpcMsg(client, data, function(err){
if (err) console.log(err+'sendOpcMsg failed');
setTimeout(function(){
if (client && client.close) client.close();
}, 2000); // 2s timeout
});
// 3.1
// emit event
self.emit('NS.SEP.SEP_OPC_SDP_OFFER', {client: client, data: data});
} else {
// hook client info
client.clntinfo = {
// user info
domain: data.offer.domain,
usrkey: data.offer.usrkey,
// client info
gid: sdp.client.gid, // client gid
vpath: sdp.client.vpath, // client vpath
vhost: sdp.client.vhost, // client vhost
vmode: sdp.client.vmode, // client vURL mode
secmode: sdp.client.secmode, // client secure mode
vtoken: sdp.client.vtoken, // client vURL secure token
clntgeoip: JSON.parse(sdp.client.geoip), // client GeoIP
clntlip: sdp.client.localIP, // client local ip/port
clntlport: sdp.client.localPort,
clntip: sdp.sdp.clntIP, // client public ip/port
clntport: sdp.sdp.clntPort,
srvip: sdp.server.ip, // server public ip/port
srvport: sdp.server.port,
srvdn: sdp.server.dn
};
// cache client obj per server/client with public ip/port
// TBD... cache in redisStore, etc, instead of memStore
ck = sdp.sdp.clntIP+':'+sdp.sdp.clntPort; // key for client ip/port
sk = sdp.server.ip+':'+sdp.server.port; // key for server ip/port
self.conn[sk] = self.conn[sk] || {};
(self.conn[sk])[ck] = client;
// send back real SDP session as answer
data.answer = sdp;
data.answer.state = SEP.SEP_OPC_STATE_READY;
// !!! for security, only return country/city of GeoIP to client
if (data.answer.client.geoip) {
data.answer.client.geoip = JSON.parse(data.answer.client.geoip);
Object.keys(data.answer.client.geoip).forEach(function(k){
if (!(k in {country: 'us', city: 'ca'})) {
data.answer.client.geoip[k] = null;
delete data.answer.client.geoip[k];
}
});
}
// send TURN server agent port info,ip is same as name-server normally
// TBD balance...
if (self.turnPorts) {
data.answer.turn = {agentport: self.turnPorts[1], agentip: sdp.server.ip};
} else {
data.answer.turn = false;
}
// 3.2
// generate security certification in secure mode
// TBD... added subject's alternate name like public/local ip, etc
if (data.offer.secmode) {
// require server to generate ssl certification
SSL.genSslCertCA(sdp.client.gid,
// client cert info
{
cn: sdp.client.vmode == vurl.URL_MODE_HOST ? '*.vurl.' + sdp.server.dn : sdp.server.dn,
ca_cert: self.sslcerts.ca && self.sslcerts.ca.cert,
ca_key: self.sslcerts.ca && self.sslcerts.ca.key,
// SSL V3 alternate names: sub-domains, public/local ip, 127.0.0.1 and Agent server IP
altname: [
///'*.*.vurl.'+sdp.server.dn, '*.vurl.local.'+sdp.server.dn, '*.*.vurl.local.'+sdp.server.dn,
///'*.vurl.'+sdp.server.dn,
client.clntinfo.clntip, client.clntinfo.clntlip, '127.0.0.1', 'localhost', '::1', 'ip6-localhost',
sdp.server.ip,
// append vlocal. subdomain
sdp.client.vmode == vurl.URL_MODE_HOST ? '*.vurl.vlocal.' + sdp.server.dn : 'vlocal.' + sdp.server.dn,
]
},
function(err, cert){
if (err) {
console.log(err+',generate security certs failed');
data.answer.secerts = null;
sendOpcMsg(client, data);
// 3.2.1
// emit event
self.emit('NS.SEP.SEP_OPC_SDP_OFFER', {client: client, data: data});
} else {
// 3.2.2
// like for *.vurl.51dese.com
data.answer.secerts = cert;
// 3.2.3
// put self-signed CA cert
data.answer.secerts.ca = self.sslcerts.ca && self.sslcerts.ca.cont;
// enable bi-direction authentication
data.answer.secerts.requestCert = true;
data.answer.secerts.rejectUnauthorized = true;
// fill NACL cert info on V2 /////////////////////////////////////////////////
if (data.offer.version && data.offer.version == 2) {
var reqdesc = {
version: '1.0',
type: 'ca',
tte: new Date().getTime() + 365*24*3600000, // one year to expire
publickey: data.offer.naclpublickey,
names: [sdp.server.dn, 'localhost'],
ips: [client.clntinfo.clntip, client.clntinfo.clntlip, '127.0.0.1']
};
var bcert = Naclcert.generate(reqdesc, self.naclcerts.ca.key.secretkey, self.naclcerts.ca.cert);
data.answer.secerts.naclcert = bcert;
}
////////////////////////////////////////////////////////////////////////
// 3.2.5
// send sdp back
sendOpcMsg(client, data);
// 3.2.6
// emit event
self.emit('NS.SEP.SEP_OPC_SDP_OFFER', {client: client, data: data});
}
});
} else {
// fill NACL cert info on V2 /////////////////////////////////////////////////
if (data.offer.version && data.offer.version == 2) {
var reqdesc = {
version: '1.0',
type: 'ca',
tte: new Date().getTime() + 365*24*3600000, // one year to expire
publickey: data.offer.naclpublickey,
names: [sdp.server.dn, 'localhost'],
ips: [client.clntinfo.clntip, client.clntinfo.clntlip, '127.0.0.1']
};
var bcert = Naclcert.generate(reqdesc, self.naclcerts.ca.key.secretkey, self.naclcerts.ca.cert);
data.answer.secerts = {};
data.answer.secerts.naclcert = bcert;
}
////////////////////////////////////////////////////////////////////////
sendOpcMsg(client, data);
// 3.2.6
// emit event
self.emit('NS.SEP.SEP_OPC_SDP_OFFER', {client: client, data: data});
}
}
});
break;
case SEP.SEP_OPC_NAT_OFFER:
// 1.
// check if user was allowed to query it
// TBD...
// 2.
// update client NAT type info
Sdp.updateClntInfo({gid: data.offer.gid, natype: data.offer.natype}, function(err){
// 3.
// fill answer opc
data.opc = SEP.SEP_OPC_NAT_ANSWER;
data.answer = {};
data.answer.state = SEP.SEP_OPC_STATE_READY;
if (err) {
console.log(err+',update client natype failed');
data.answer.ready = false;
} else {
console.log('update client natype successfully');
data.answer.ready = true;
}
// 4.
// send message back
sendOpcMsg(client, data);
// 4.1
// emit event
self.emit('NS.SEP.SEP_OPC_NAT_OFFER', {client: client, data: data});
});
break;
case SEP.SEP_OPC_HEART_BEAT_OFFER:
// 1.
// check if user was allowed to query it
// TBD...
// 2.
// heart-beat check response
// 2.1
// fill answer opc
data.opc = SEP.SEP_OPC_HEART_BEAT_ANSWER;
data.answer = {};
data.answer.state = SEP.SEP_OPC_STATE_READY;
data.answer.ready = true;
// fill server timestamp
data.answer.timeAt = Date.now();
// 3.
// send message back
sendOpcMsg(client, data);
// 3.1
// emit event
self.emit('NS.SEP.SEP_OPC_HEART_BEAT_OFFER', {client: client, data: data});
break;
case SEP.SEP_OPC_STUN_OFFER:
if (Debug) console.log('stun.offer:'+JSON.stringify(data));
// 1.
// check offer credit
// TBD... policy
// - allow to public peer
// - allow to test user
// - allow to user-self peer
// - allow to peer authenticated ACL list
/*
console.log('self.conn.skeys:');
for (k in self.conn) {
console.log(', '+k+',ckeys:');
for (var k1 in self.conn[k]) {
console.log(', '+k1);
}
}
console.log('offer.mine:'+data.offer.mine.ip+':'+data.offer.mine.port+'@'+
client.clntinfo.srvip+':'+client.clntinfo.srvport);
console.log('offer.peer:'+data.offer.peer.ip+':'+data.offer.peer.port+'@'+
client.clntinfo.srvip+':'+client.clntinfo.srvport);
*/
// TBD... clients cache load balance
/*var ck = data.offer.mine.ip+data.offer.mine.port;
for (var sk in self.conn) {
if (ck in self.conn[sk]) {
peerclnt = (self.conn[sk])[ck];
break;
}
}*/
/*mineclnt = (self.conn[client.clntinfo.srvip+':'+client.clntinfo.srvport])
[data.offer.mine.ip+':'+data.offer.mine.port];*/
mineclnt = client; // current client is always mine
peerclnt = (self.conn[client.clntinfo.srvip+':'+client.clntinfo.srvport])
[data.offer.peer.ip+':'+data.offer.peer.port];
// 1.1
// check on user for authentication
// only allow user connect to user-self, public user and test user
// TBD... Policy-Based_ACL
if (mineclnt.clntinfo && mineclnt.clntinfo.domain && mineclnt.clntinfo.usrkey &&
peerclnt.clntinfo && peerclnt.clntinfo.domain && peerclnt.clntinfo.usrkey &&
// 1.1.1
// !!! allow connect to user-self
((mineclnt.clntinfo.domain === peerclnt.clntinfo.domain && mineclnt.clntinfo.usrkey === peerclnt.clntinfo.usrkey) ||
// 1.1.2
// !!! allow connect to public user
(mineclnt.clntinfo.domain === peerclnt.clntinfo.domain && 'public' === peerclnt.clntinfo.usrkey) ||
// 1.1.3
// !!! allow connect to test user
(mineclnt.clntinfo.domain === peerclnt.clntinfo.domain &&
mineclnt.clntinfo.usrkey.match(/(A|B|C)/gi) &&
peerclnt.clntinfo.usrkey.match(/(A|B|C)/gi)))) {
///
} else {
console.log('!!!DDOS attack,no permission to get STUN session');
// 1.1.3
// send STUN_ANSWER to myself client
data.offer.isInitiator = true;
data.opc = SEP.SEP_OPC_STUN_ANSWER;
data.answer = {};
data.answer.state = SEP.SEP_OPC_STATE_FAIL;
data.answer.ready = false;
// 1.1.5
// close after 2s
sendOpcMsg(mineclnt, data, function(err){
if (err) console.log(err+'sendOpcMsg failed');
setTimeout(function(){
if (mineclnt && mineclnt.close) mineclnt.close();
}, 2000); // 2s timeout
});
if (Debug) console.log('mineclnt stun.data.offer:'+JSON.stringify(data.offer));
// 1.1.6
// emit event with initiator
self.emit('NS.SEP.SEP_OPC_STUN_OFFER', {client: mineclnt, data: data});
break;
}
// 2.
// fill punch hole offer
data.opc = SEP.SEP_OPC_PUNCH_OFFER;
// 3.
// send punch hole offer to both peers
// 3.1
// keep data.seqno as stun initiator
// send punch hole offer to myself client
data.offer.isInitiator = true;
sendOpcMsg(mineclnt, data);
if (Debug) console.log('mineclnt stun.data.offer:'+JSON.stringify(data.offer));
// emit event with initiator
self.emit('NS.SEP.SEP_OPC_STUN_OFFER', {client: mineclnt, data: data});
// swap offer.mine and offer.peer to assemble PUNCH offer for peer client
var tmp = data.offer.mine;
data.offer.mine = data.offer.peer;
data.offer.peer = tmp;
// send punch hole offer to peer client
data.offer.isInitiator = false;
sendOpcMsg(peerclnt, data);
if (Debug) console.log('peerclnt stun.data.offer:'+JSON.stringify(data.offer));
break;
case SEP.SEP_OPC_TURN_OFFER:
if (Debug) console.log('turn.offer:'+JSON.stringify(data));
// 1.
// check offer credit
// TBD... policy
// - allow to public peer
// - allow to test user
// - allow to user-self peer
// - allow to peer authenticated ACL list
/*
console.log('self.conn.skeys:');
for (k in self.conn) {
console.log(', '+k+',ckeys:');
for (var k1 in self.conn[k]) {
console.log(', '+k1);
}
}
console.log('offer.mine:'+data.offer.mine.ip+':'+data.offer.mine.port+'@'+
client.clntinfo.srvip+':'+client.clntinfo.srvport);
console.log('offer.peer:'+data.offer.peer.ip+':'+data.offer.peer.port+'@'+
client.clntinfo.srvip+':'+client.clntinfo.srvport);
*/
// TBD... clients cache load balance
/*var ck = data.offer.mine.ip+data.offer.mine.port;
for (var sk in self.conn) {
if (ck in self.conn[sk]) {
peerclnt = (self.conn[sk])[ck];
break;
}
}*/
/*mineclnt = (self.conn[client.clntinfo.srvip+':'+client.clntinfo.srvport])
[data.offer.mine.ip+':'+data.offer.mine.port];*/
mineclnt = client; // current client is always mine
peerclnt = (self.conn[client.clntinfo.srvip+':'+client.clntinfo.srvport])
[data.offer.peer.ip+':'+data.offer.peer.port];
// 1.1
// check on user for authentication
// only allow user connect to user-self, public user and test user
// TBD... Policy-Based_ACL
if (mineclnt.clntinfo && mineclnt.clntinfo.domain && mineclnt.clntinfo.usrkey &&
peerclnt.clntinfo && peerclnt.clntinfo.domain && peerclnt.clntinfo.usrkey &&
// 1.1.1
// !!! allow connect to user-self
((mineclnt.clntinfo.domain === peerclnt.clntinfo.domain && mineclnt.clntinfo.usrkey === peerclnt.clntinfo.usrkey) ||
// 1.1.2
// !!! allow connect to public user
(mineclnt.clntinfo.domain === peerclnt.clntinfo.domain && 'public' === peerclnt.clntinfo.usrkey) ||
// 1.1.3
// !!! allow connect to test user
(mineclnt.clntinfo.domain === peerclnt.clntinfo.domain &&
mineclnt.clntinfo.usrkey.match(/(A|B|C)/gi) &&
peerclnt.clntinfo.usrkey.match(/(A|B|C)/gi)))) {
///
} else {
console.log('!!!DDOS attack,no permission to get TURN session');
// 1.1.3
// send TURN_ANSWER to myself client
data.offer.isInitiator = true;
data.opc = SEP.SEP_OPC_TURN_ANSWER;
data.answer = {};
data.answer.state = SEP.SEP_OPC_STATE_FAIL;
data.answer.ready = false;
// 1.1.5
// close after 2s
sendOpcMsg(mineclnt, data, function(err){
if (err) console.log(err+'sendOpcMsg failed');
setTimeout(function(){
if (mineclnt && mineclnt.close) mineclnt.close();
}, 2000); // 2s timeout
});
if (Debug) console.log('mineclnt turn.data.offer:'+JSON.stringify(data.offer));
// 1.1.6
// emit event with initiator
self.emit('NS.SEP.SEP_OPC_TURN_OFFER', {client: mineclnt, data: data});
break;
}
// 2.
// check if Peer is ready for TURN/AGENT relay
// - find TURN/PROXY routing entry by peer's vURL root path
// - if TURN/AGENT ready, but no routing entry, just create one
// notes: by now we treat name-client's vURL root path as /vurl/:gid/
// TBD... vURL balance by name-client' GID
data.opc = SEP.SEP_OPC_TURN_ANSWER;
data.answer = {};
// every name-client has vURL based on vhost or vpath
var vurle = (data.offer.peer.vmode === vurl.URL_MODE_PATH) ? data.offer.peer.vpath : data.offer.peer.vhost;
vURL.get(vurle, function(err, routing){
if (err || !routing || !routing.turn) {
console.log('unknown TURN/PROXY routing entry');
data.answer.state = SEP.SEP_OPC_STATE_FAIL;
data.answer.ready = false;
// 2.1
// send turn answer to myself client
/*mineclnt = (self.conn[client.clntinfo.srvip+':'+client.clntinfo.srvport])
[data.offer.mine.ip+':'+data.offer.mine.port];*/
mineclnt = client; // current client is always mine
data.answer.isInitiator = true;
sendOpcMsg(mineclnt, data);
// 2.1.1
// emit event with initiator
self.emit('NS.SEP.SEP_OPC_TURN_OFFER', {client: mineclnt, data: data});
} else {
// 3.
// persistent TURN session
var turn = new Turn({
// session info
sid : UUID.v4(),
proto : 'udp',
mode : data.offer.mode,
// client info
minenatype: data.offer.mine.natype,
mineid : data.offer.mine.gid,
mineIP : data.offer.mine.ip,
minePort : data.offer.mine.port,
peernatype: data.offer.peer.natype,
peerid : data.offer.peer.gid,
peerIP : data.offer.peer.ip,
peerPort : data.offer.peer.port,
// turn server info got by vURL lookup
srvpublicDN : routing.turn.dn,
srvpublicIP : routing.turn.ipaddr,
srvproxyPort: routing.turn.proxyport,
srvagentPort: routing.turn.agentport
});
turn.saveOupdate(function(err, turn){
if (err) {
console.log(err+',record turn session failed');
data.answer.state = SEP.SEP_OPC_STATE_FAIL;
data.answer.ready = false;
} else {
// fill answer info
if (Debug) console.log('saved turn session successfully:'+JSON.stringify(turn));
data.answer.state = SEP.SEP_OPC_STATE_READY;
data.answer.ready = true;
data.answer.peer = turn.peer;
data.answer.mine = turn.mine;
data.answer.turn = turn.session;
// fill TURN/PROXY vURL vpath or vhost info
data.answer.turn.vpath = data.offer.peer.vpath;
data.answer.turn.vhost = data.offer.peer.vhost;
data.answer.turn.vmode = data.offer.peer.vmode;
data.answer.turn.vtoken = data.offer.peer.vtoken;
// fill TURN security mode as peer security mode
data.answer.turn.secmode = data.offer.peer.secmode;
}
// 4.
// send turn answer to both peers
// - initiator will setup connection to turn/proxy server, then by turn/agent-client to peer
// - responsor will allow connection from turn/agent-client by turn/proxy server from initiator
// keep data.seqno as turn initiator
// 4.1
// send turn answer to myself client
data.answer.isInitiator = true;
sendOpcMsg(mineclnt, data);
if (Debug) console.log('mineclnt turn.data.offer:'+JSON.stringify(data.offer));
// 4.1.1
// emit event with initiator
self.emit('NS.SEP.SEP_OPC_TURN_OFFER', {client: mineclnt, data: data});
// 4.2
// swap offer.mine and offer.peer to assemble TURN answer for peer client
// notes: only send it when find TURN/PROXY routing entry
if (data.answer.state === SEP.SEP_OPC_STATE_READY) {
var tmp = data.offer.mine;
data.offer.mine = data.offer.peer;
data.offer.peer = tmp;
// send turn answer to peer client
data.answer.isInitiator = false;
sendOpcMsg(peerclnt, data);
if (Debug) console.log('peerclnt turn.data.offer:'+JSON.stringify(data.offer));
}
});
}
});
break;
case SEP.SEP_OPC_PUNCH_ANSWER:
// 1.
// check answer credit
// 2.
// send STUN answer to initiator
// Algorithem:
// - for both of asymmmetric NAT/FW, send message from Initiator side to name-server
// - for one asymmetric NAT/FW, another's symmetric, send message from symmetric side
// - for both of symmmetric NAT/FW, send message from Initiator side to name-server
// 2.1
// fill STUN answer
data.opc = SEP.SEP_OPC_STUN_ANSWER;
if (data.answer.state === SEP.SEP_OPC_STATE_READY) {
data.answer.ready = true;
// persist STUN session
var stun = new Stun({
sid : UUID.v4(),
proto : 'udp',
mode : data.offer.mode,
minenatype: data.offer.isInitiator ? data.offer.mine.natype : data.offer.peer.natype,
mineid : data.offer.isInitiator ? data.offer.mine.gid : data.offer.peer.gid,
peernatype: !data.offer.isInitiator ? data.offer.mine.natype : data.offer.peer.natype,
peerid : !data.offer.isInitiator ? data.offer.mine.gid : data.offer.peer.gid,
// MUST extract external ip/port from answer instead of offer.mine/peer
mineIP : data.offer.isInitiator ? ((data.answer.cinfo && data.answer.cinfo.moaddr) || data.offer.mine.ip) :
((data.answer.cinfo && data.answer.cinfo.poaddr) || data.offer.peer.ip),
minePort : data.offer.isInitiator ? ((data.answer.cinfo && data.answer.cinfo.moport) || data.offer.mine.port) :
((data.answer.cinfo && data.answer.cinfo.poport) || data.offer.peer.port),
peerIP : !data.offer.isInitiator ? ((data.answer.cinfo && data.answer.cinfo.moaddr) || data.offer.mine.ip) :
((data.answer.cinfo && data.answer.cinfo.poaddr) || data.offer.peer.ip),
peerPort : !data.offer.isInitiator ? ((data.answer.cinfo && data.answer.cinfo.moport) || data.offer.mine.port) :
((data.answer.cinfo && data.answer.cinfo.poport) || data.offer.peer.port)
});
stun.saveOupdate(function(err, stun){
if (err) {
console.log(err+',record stun session failed');
data.answer.state = SEP.SEP_OPC_STATE_FAIL;
data.answer.ready = false;
} else {
// fill answer info
if (Debug) console.log('saved stun session successfully:'+JSON.stringify(stun));
data.answer.state = SEP.SEP_OPC_STATE_READY;
data.answer.ready = true;
data.answer.peer = stun.peer;
data.answer.mine = stun.mine;
data.answer.stun = stun.session;
}
// 2.2
// find connection of initiator
// TBD... mine/peer client load balance
/*var ck = data.offer.mine.ip+data.offer.mine.port;
for (var sk in self.conn) {
if (ck in self.conn[sk]) {
mineclnt = (self.conn[sk])[ck];
break;
}
}*/
if (data.offer.isInitiator) {
// current client is initiator
mineclnt = client;
} else {
// peer client is initiator
mineclnt = (self.conn[client.clntinfo.srvip+':'+client.clntinfo.srvport])
[data.offer.peer.ip+':'+data.offer.peer.port];
}
// 2.3.
// send STUN answer back
// keep data.seqno as stun initiator
sendOpcMsg(mineclnt, data);
// 2.3.1
// emit event with initiator
self.emit('NS.SEP.SEP_OPC_PUNCH_ANSWER', {client: mineclnt, data: data});
});
} else {
data.answer.state = SEP.SEP_OPC_STATE_FAIL;
data.answer.ready =false;
// 2.2
// find connection of initiator
// TBD... mine client load balance
/*var ck = data.offer.mine.ip+data.offer.mine.port;
for (var sk in self.conn) {
if (ck in self.conn[sk]) {
mineclnt = (self.conn[sk])[ck];
break;
}
}*/
if (data.offer.isInitiator) {
// current client is initiator
mineclnt = client;
} else {
// peer client is initiator
mineclnt = (self.conn[client.clntinfo.srvip+':'+client.clntinfo.srvport])
[data.offer.peer.ip+':'+data.offer.peer.port];
}
// 2.3.
// send STUN answer back
// keep data.seqno as stun initiator
sendOpcMsg(mineclnt, data);
// 2.3.1
// emit event with initiator
self.emit('NS.SEP.SEP_OPC_PUNCH_ANSWER', {client: mineclnt, data: data});
}
break;
// offer/answer opc <- /////////////////////////////////////////////
// user management opc -> //////////////////////////////////////////
case SEP.SEP_OPC_CLNT_SDP_OFFER:
// 1.
// check if user was allowed to query it
// TBD...
// 2.
// query sdp info
Sdp.getSdpByClnt(('string' === typeof data.offer.clnt) ?
data.offer.clnt : Sdp.genClntid(data.offer.clnt),
function(err, sdps){
// 3.
// send back CLNT_SDP answer
data.opc = SEP.SEP_OPC_CLNT_SDP_ANSWER;
data.answer = {};
if (err) {
console.log(err+',query sdp session failed');
// send back sdp session as answer
data.answer.sdps = [];
data.answer.state = SEP.SEP_OPC_STATE_FAIL;
} else {
// send back real sdp session as answer
data.answer.sdps = sdps;
data.answer.state = SEP.SEP_OPC_STATE_READY;
}
sendOpcMsg(client, data);
// 3.1
// emit event
self.emit('NS.SEP.SEP_OPC_CLNT_SDP_OFFER', {client: mineclnt, data: data});