forked from PeterWaher/IoTGateway
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXmppServerlessMessaging.cs
More file actions
711 lines (625 loc) · 19.5 KB
/
XmppServerlessMessaging.cs
File metadata and controls
711 lines (625 loc) · 19.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
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
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using System.Text;
using System.Xml;
using Waher.Events;
using Waher.Networking.Sniffers;
using Waher.Networking.PeerToPeer;
namespace Waher.Networking.XMPP.P2P
{
/// <summary>
/// Event handler for peer connection callbacks.
/// </summary>
/// <param name="Sender">Sender of event.</param>
/// <param name="e">Event arguments.</param>
public delegate void PeerConnectionEventHandler(object Sender, PeerConnectionEventArgs e);
/// <summary>
/// Class managing peer-to-peer serveless XMPP communication.
/// </summary>
public class XmppServerlessMessaging : Sniffable, IDisposable
{
private Dictionary<string, PeerState> peersByFullJid = new Dictionary<string, PeerState>(StringComparer.CurrentCultureIgnoreCase);
private readonly Dictionary<string, AddressInfo> addressesByFullJid = new Dictionary<string, AddressInfo>(StringComparer.CurrentCultureIgnoreCase);
private readonly Dictionary<string, Dictionary<int, AddressInfo>> addressesByExternalIPPort = new Dictionary<string, Dictionary<int, AddressInfo>>();
private readonly Dictionary<string, Dictionary<int, AddressInfo>> addressesByLocalIPPort = new Dictionary<string, Dictionary<int, AddressInfo>>();
private PeerToPeerNetwork p2pNetwork = null;
private string fullJid;
/// <summary>
/// Class managing peer-to-peer serveless XMPP communication.
/// </summary>
/// <param name="ApplicationName">Name of application, as it will be registered in Internet Gateways.</param>
/// <param name="FullJid">Bare JID of local end-point.</param>
/// <param name="Sniffers">Sniffers</param>
public XmppServerlessMessaging(string ApplicationName, string FullJid, params ISniffer[] Sniffers)
: this(ApplicationName, FullJid, PeerToPeerNetwork.DefaultPort, PeerToPeerNetwork.DefaultPort,
PeerToPeerNetwork.DefaultBacklog, Sniffers)
{
}
/// <summary>
/// Class managing peer-to-peer serveless XMPP communication.
/// </summary>
/// <param name="ApplicationName">Name of application, as it will be registered in Internet Gateways.</param>
/// <param name="FullJid">Bare JID of local end-point.</param>
/// <param name="LocalPort">Desired local port number. If 0, a dynamic port number will be assigned.</param>
/// <param name="ExternalPort">Desired external port number. If 0, a dynamic port number will be assigned.</param>
/// <param name="Sniffers">Sniffers</param>
public XmppServerlessMessaging(string ApplicationName, string FullJid, ushort LocalPort, ushort ExternalPort, params ISniffer[] Sniffers)
: this(ApplicationName, FullJid, LocalPort, ExternalPort, PeerToPeerNetwork.DefaultBacklog, Sniffers)
{
}
/// <summary>
/// Class managing peer-to-peer serveless XMPP communication.
/// </summary>
/// <param name="ApplicationName">Name of application, as it will be registered in Internet Gateways.</param>
/// <param name="FullJid">Bare JID of local end-point.</param>
/// <param name="LocalPort">Desired local port number. If 0, a dynamic port number will be assigned.</param>
/// <param name="ExternalPort">Desired external port number. If 0, a dynamic port number will be assigned.</param>
/// <param name="Backlog">Connection backlog.</param>
/// <param name="Sniffers">Sniffers</param>
public XmppServerlessMessaging(string ApplicationName, string FullJid, ushort LocalPort, ushort ExternalPort, int Backlog,
params ISniffer[] Sniffers)
: base(Sniffers)
{
this.fullJid = FullJid;
this.p2pNetwork = new PeerToPeerNetwork(ApplicationName, LocalPort, ExternalPort, Backlog, Sniffers)
{
EncapsulatePackets = false
};
// TODO: Implement support for NAT-PMP
this.p2pNetwork.OnPeerConnected += P2PNetwork_OnPeerConnected;
}
/// <summary>
/// Peer-to-peer network.
/// </summary>
public PeerToPeerNetwork Network
{
get { return this.p2pNetwork; }
}
/// <summary>
/// Full JID
/// </summary>
public string FullJid
{
get { return this.fullJid; }
set { this.fullJid = value; }
}
private Task P2PNetwork_OnPeerConnected(object Listener, PeerConnection Peer)
{
PeerState _ = new PeerState(Peer, this);
this.Information("Peer connected from " + Peer.RemoteEndpoint.ToString());
return Task.CompletedTask;
}
/// <summary>
/// Removes a JID from the recognized set of JIDs.
/// </summary>
/// <param name="FullJID">Full JID.</param>
public void RemovePeerAddresses(string FullJID)
{
string ThisExternalIp = this.p2pNetwork.ExternalAddress is null ? string.Empty : this.p2pNetwork.ExternalAddress.ToString();
lock (this.addressesByFullJid)
{
if (this.addressesByFullJid.TryGetValue(FullJID, out AddressInfo Info))
{
this.addressesByFullJid.Remove(FullJID);
if (this.addressesByExternalIPPort.TryGetValue(Info.ExternalIp, out Dictionary<int, AddressInfo> Infos))
{
if (Infos.Remove(Info.ExternalPort) && Infos.Count == 0)
this.addressesByExternalIPPort.Remove(Info.ExternalIp);
}
if (Info.ExternalIp == ThisExternalIp)
{
if (this.addressesByLocalIPPort.TryGetValue(Info.LocalIp, out Infos))
{
if (Infos.Remove(Info.LocalPort) && Infos.Count == 0)
this.addressesByLocalIPPort.Remove(Info.LocalIp);
}
}
}
else
return;
}
this.Information("Removing JID from set of recognized JIDs: " + FullJID);
PeerAddressEventHandler h = this.PeerAddressRemoved;
if (!(h is null))
{
try
{
h(this, new PeerAddressEventArgs(FullJID, string.Empty, 0, string.Empty, 0));
}
catch (Exception ex)
{
Log.Critical(ex);
}
}
}
/// <summary>
/// Event raised when address information about a peer has been removed.
/// </summary>
public event PeerAddressEventHandler PeerAddressRemoved = null;
/// <summary>
/// Reports recognized peer addresses.
/// </summary>
/// <param name="FullJID">XMPP Address (full JID).</param>
/// <param name="ExternalIp">External IP address.</param>
/// <param name="ExternalPort">External Port number.</param>
/// <param name="LocalIp">Local IP address.</param>
/// <param name="LocalPort">Local Port number.</param>
public void ReportPeerAddresses(string FullJID, string ExternalIp, int ExternalPort, string LocalIp, int LocalPort)
{
Dictionary<int, AddressInfo> Infos;
string ThisExternalIp;
if (this.p2pNetwork.ExternalAddress is null)
ThisExternalIp = string.Empty;
else
ThisExternalIp = this.p2pNetwork.ExternalAddress.ToString();
lock (this.addressesByFullJid)
{
if (this.addressesByFullJid.TryGetValue(FullJID, out AddressInfo Info))
{
if (Info.ExternalIp == ExternalIp && Info.ExternalPort == ExternalPort &&
Info.LocalIp == LocalIp && Info.LocalPort == LocalPort)
{
return;
}
if (Info.ExternalIp != ExternalIp)
{
if (this.addressesByExternalIPPort.TryGetValue(Info.ExternalIp, out Infos))
{
if (Infos.Remove(Info.ExternalPort) && Infos.Count == 0)
this.addressesByExternalIPPort.Remove(Info.ExternalIp);
}
}
if (ExternalIp == ThisExternalIp && Info.LocalIp != LocalIp)
{
if (this.addressesByLocalIPPort.TryGetValue(Info.LocalIp, out Infos))
{
if (Infos.Remove(Info.LocalPort) && Infos.Count == 0)
this.addressesByLocalIPPort.Remove(Info.LocalIp);
}
}
}
Info = new AddressInfo(FullJID, ExternalIp, ExternalPort, LocalIp, LocalPort);
this.addressesByFullJid[FullJID] = Info;
if (!this.addressesByExternalIPPort.TryGetValue(ExternalIp, out Infos))
{
Infos = new Dictionary<int, AddressInfo>();
this.addressesByExternalIPPort[ExternalIp] = Infos;
}
Infos[ExternalPort] = Info;
if (ExternalIp == ThisExternalIp)
{
if (!this.addressesByLocalIPPort.TryGetValue(LocalIp, out Infos))
{
Infos = new Dictionary<int, AddressInfo>();
this.addressesByLocalIPPort[LocalIp] = Infos;
}
Infos[LocalPort] = Info;
}
}
this.Information("P2P information available for " + FullJID + ". External: " + ExternalIp + ":" + ExternalPort.ToString() +
", Local: " + LocalIp + ":" + LocalPort.ToString());
PeerAddressEventHandler h = this.PeerAddressReceived;
if (!(h is null))
{
try
{
h(this, new PeerAddressEventArgs(FullJID, ExternalIp, ExternalPort, LocalIp, LocalPort));
}
catch (Exception ex)
{
Log.Critical(ex);
}
}
}
/// <summary>
/// Event raised when address information about a peer has been received.
/// </summary>
public event PeerAddressEventHandler PeerAddressReceived = null;
internal void AuthenticatePeer(PeerConnection Peer, string FullJID)
{
AddressInfo Info;
lock (this.addressesByFullJid)
{
if (!this.addressesByFullJid.TryGetValue(FullJID, out Info))
throw new XmppException("Peer JID " + FullJID + " not recognized.");
}
if (Info.ExternalIp == this.p2pNetwork.ExternalAddress.ToString())
{
if (Peer.RemoteEndpoint.Address.ToString() != Info.LocalIp)
{
throw new XmppException("Expected connection from " + Info.LocalIp + ", but was from " +
Peer.RemoteEndpoint.Address.ToString());
}
}
else
{
if (Peer.RemoteEndpoint.Address.ToString() != Info.ExternalIp)
{
throw new XmppException("Expected connection from " + Info.ExternalIp + ", but was from " +
Peer.RemoteEndpoint.ToString());
}
}
// End-to-end encryption will asure communication is only read by the indended receiver.
}
internal void PeerAuthenticated(PeerState State)
{
lock (this.peersByFullJid)
{
this.peersByFullJid[State.RemoteFullJid] = State;
}
this.Information("Peer authenticated: " + State.RemoteFullJid);
}
internal void NewXmppClient(XmppClient Client, string LocalJid, string RemoteJid)
{
this.Information("Serverless XMPP connection established with " + RemoteJid);
/*foreach (ISniffer Sniffer in this.Sniffers)
Client.Add(Sniffer);*/
PeerConnectionEventHandler h = this.OnNewXmppClient;
if (!(h is null))
{
try
{
h(this, new PeerConnectionEventArgs(Client, null, LocalJid, RemoteJid));
}
catch (Exception ex)
{
Log.Critical(ex);
}
}
}
/// <summary>
/// Event raised when a new XMPP client has been created.
/// </summary>
public event PeerConnectionEventHandler OnNewXmppClient = null;
internal void PeerClosed(PeerState State)
{
this.Information("Serverless XMPP connection with " + State.RemoteFullJid + " closed.");
if (!(this.peersByFullJid is null))
{
lock (this.peersByFullJid)
{
if (this.peersByFullJid.TryGetValue(State.RemoteFullJid, out PeerState State2) && State2 == State)
this.peersByFullJid.Remove(State.RemoteFullJid);
}
}
}
/// <summary>
/// Gets a peer XMPP connection.
/// </summary>
/// <param name="FullJID">Bare JID of peer to connect to.</param>
/// <param name="Callback">Method to call when connection is established.</param>
/// <param name="State">State object to pass on to callback method.</param>
public void GetPeerConnection(string FullJID, PeerConnectionEventHandler Callback, object State)
{
this.GetPeerConnection(FullJID, Callback, State, this.OnResynch);
}
/// <summary>
/// Event raised when the peer-to-peer connection parameters need to be updated for a given remote JID.
/// </summary>
public event ResynchEventHandler OnResynch = null;
/// <summary>
/// If it is possible to connect directly to a given peer, given it's bare JID.
/// </summary>
/// <param name="FullJID">Full JID.</param>
/// <returns>If it is possible to connect directly to the peer.</returns>
public bool CanConnectToPeer(string FullJID)
{
AddressInfo Info;
lock (this.addressesByFullJid)
{
if (!this.addressesByFullJid.TryGetValue(FullJID, out Info))
return false;
}
return !string.IsNullOrEmpty(Info.ExternalIp);
}
/// <summary>
/// Gets peer-to-peer address information
/// </summary>
/// <param name="FullJID">Full JID</param>
/// <param name="Address">IP address information</param>
/// <returns></returns>
public bool TryGetAddressInfo(string FullJID, out AddressInfo Address)
{
lock (this.addressesByFullJid)
{
return this.addressesByFullJid.TryGetValue(FullJID, out Address);
}
}
private void GetPeerConnection(string FullJID, PeerConnectionEventHandler Callback, object State, ResynchEventHandler ResynchMethod)
{
PeerState Result;
PeerState Old = null;
AddressInfo Info;
string Header = null;
bool b;
if (this.p2pNetwork is null || this.p2pNetwork.State != PeerToPeerNetworkState.Ready)
{
if (!(Callback is null))
{
try
{
Callback(this, new PeerConnectionEventArgs(null, State, this.fullJid, FullJID));
}
catch (Exception ex)
{
Log.Critical(ex);
}
}
return;
}
lock (this.addressesByFullJid)
{
b = this.addressesByFullJid.TryGetValue(FullJID, out Info);
}
if (!b)
{
Callback(this, new PeerConnectionEventArgs(null, State, this.fullJid, FullJID));
return;
}
lock (this.peersByFullJid)
{
b = this.peersByFullJid.TryGetValue(FullJID, out Result);
if (b)
{
if (Result.AgeSeconds >= 30 && (Result.HasCallbacks || Result.XmppClient is null || !Result.Peer.Tcp.Connected))
{
this.peersByFullJid.Remove(FullJID);
Old = Result;
Result = null;
b = false;
}
else if (Result.State != XmppState.Connected)
{
Result.AddCallback(Callback, State);
return;
}
}
if (!b)
{
Header = "<?xml version='1.0'?><stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' from='" +
this.fullJid + "' to='" + FullJID + "' version='1.0'>";
Result = new PeerState(null, this, FullJID, Header, "</stream:stream>", string.Empty, 1.0, Callback, State);
this.peersByFullJid[FullJID] = Result;
}
}
if (b)
{
try
{
Callback(this, new PeerConnectionEventArgs(Result.XmppClient, State, this.fullJid, FullJID));
}
catch (Exception ex)
{
Log.Critical(ex);
}
return;
}
else if (!(Old is null))
{
Old.CallCallbacks();
Old.Dispose();
}
Task.Run(async () =>
{
PeerConnection Connection;
try
{
Connection = await this.ConnectToAsync(FullJID, Info);
}
catch (Exception ex)
{
this.Exception(ex);
Connection = null;
if (!(ResynchMethod is null))
{
try
{
ResynchEventArgs e = new ResynchEventArgs(FullJID, (sender, e2) =>
{
try
{
if (e2.Ok)
this.GetPeerConnection(FullJID, Callback, State, null);
else
{
lock (this.peersByFullJid)
{
this.peersByFullJid.Remove(FullJID);
}
Result.CallCallbacks();
}
}
catch (Exception ex2)
{
Log.Critical(ex2);
}
});
ResynchMethod(this, e);
}
catch (Exception ex2)
{
Log.Critical(ex2);
}
return;
}
}
if (Connection is null)
{
lock (this.peersByFullJid)
{
this.peersByFullJid.Remove(FullJID);
}
Result.CallCallbacks();
}
else
{
Result.Peer = Connection;
Connection.Start((sender, e) =>
{
if (!(ResynchMethod is null))
{
try
{
ResynchMethod(this, new ResynchEventArgs(FullJID, async (sender2, e2) =>
{
try
{
if (e2.Ok)
{
Result.Peer = null;
Connection = await this.ConnectToAsync(FullJID, Info);
Result.Peer = Connection;
Connection.Start();
Result.HeaderSent = true;
await Result.SendAsync(Header);
this.TransmitText(Header);
}
else
Result.CallCallbacks();
}
catch (Exception ex)
{
Log.Critical(ex);
}
}));
}
catch (Exception ex)
{
Log.Critical(ex);
Result.CallCallbacks();
}
}
else
Result.CallCallbacks();
});
Result.HeaderSent = true;
await Result.SendAsync(Header);
this.TransmitText(Header);
}
});
}
private async Task<PeerConnection> ConnectToAsync(string FullJID, AddressInfo Info)
{
PeerConnection Connection;
string Ip;
int Port;
if (Info.ExternalIp == this.p2pNetwork.ExternalAddress.ToString())
{
Ip = Info.LocalIp;
Port = Info.LocalPort;
}
else
{
Ip = Info.ExternalIp;
Port = Info.ExternalPort;
}
if (IPAddress.TryParse(Ip, out IPAddress Addr))
{
this.Information("Connecting to " + Ip + ":" + Port.ToString() + " (" + FullJID + ")");
Connection = await this.p2pNetwork.ConnectToPeer(new IPEndPoint(Addr, Port));
this.Information("Connected to to " + Ip + ":" + Port.ToString() + " (" + FullJID + ")");
}
else
Connection = null;
return Connection;
}
/// <summary>
/// <see cref="IDisposable.Dispose"/>
/// </summary>
public void Dispose()
{
this.p2pNetwork?.Dispose();
this.p2pNetwork = null;
if (!(this.peersByFullJid is null))
{
PeerState[] States;
lock (this.peersByFullJid)
{
States = new PeerState[this.peersByFullJid.Count];
this.peersByFullJid.Values.CopyTo(States, 0);
this.peersByFullJid.Clear();
}
this.peersByFullJid = null;
foreach (PeerState State in States)
{
State.ClearCallbacks();
State.Close();
}
}
}
/// <summary>
/// Appends P2P information to XML.
/// </summary>
/// <param name="Xml">XML Output.</param>
public void AppendP2pInfo(StringBuilder Xml)
{
if (this.p2pNetwork != null && this.p2pNetwork.State == PeerToPeerNetworkState.Ready)
{
Xml.Append("<p2p xmlns='");
Xml.Append(EndpointSecurity.IoTHarmonizationP2P);
Xml.Append("' extIp='");
Xml.Append(this.p2pNetwork.ExternalAddress.ToString());
Xml.Append("' extPort='");
Xml.Append(this.p2pNetwork.ExternalEndpoint.Port.ToString());
Xml.Append("' locIp='");
Xml.Append(this.p2pNetwork.LocalAddress.ToString());
Xml.Append("' locPort='");
Xml.Append(this.p2pNetwork.LocalEndpoint.Port.ToString());
Xml.Append("'/>");
}
}
/// <summary>
/// Adds P2P address information about a peer.
/// </summary>
/// <param name="FullJID">Full JID of peer.</param>
/// <param name="P2P">P2P address information.</param>
/// <returns>If information was found and added.</returns>
public bool AddPeerAddressInfo(string FullJID, XmlElement P2P)
{
string ExtIp = null;
int? ExtPort = null;
string LocIp = null;
int? LocPort = null;
if (!(P2P is null))
{
foreach (XmlAttribute Attr in P2P.Attributes)
{
switch (Attr.Name)
{
case "extIp":
if (IPAddress.TryParse(Attr.Value, out IPAddress Addr) && InternetGatewayRegistrator.IsPublicAddress(Addr))
ExtIp = Attr.Value;
break;
case "extPort":
if (int.TryParse(Attr.Value, out int i) && i >= 0 && i < 65536)
ExtPort = i;
else
return false;
break;
case "locIp":
LocIp = Attr.Value;
break;
case "locPort":
if (int.TryParse(Attr.Value, out i) && i >= 0 && i < 65536)
LocPort = i;
else
return false;
break;
}
}
}
if (ExtIp != null && ExtPort.HasValue && LocIp != null && LocPort.HasValue)
{
this.ReportPeerAddresses(FullJID, ExtIp, ExtPort.Value, LocIp, LocPort.Value);
return true;
}
else
{
this.RemovePeerAddresses(FullJID);
return false;
}
}
}
}