-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathXmppClient.cs
More file actions
7746 lines (6702 loc) · 245 KB
/
XmppClient.cs
File metadata and controls
7746 lines (6702 loc) · 245 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
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
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
#if WINDOWS_UWP
using Windows.Networking.Sockets;
using Windows.Security.Cryptography.Certificates;
#else
using System.Security.Cryptography.X509Certificates;
#endif
using Waher.Content;
using Waher.Content.Xml;
using Waher.Events;
using Waher.Networking.Sniffers;
using Waher.Networking.XMPP.Authentication;
using Waher.Networking.XMPP.AuthenticationErrors;
using Waher.Networking.XMPP.StanzaErrors;
using Waher.Networking.XMPP.StreamErrors;
using Waher.Networking.XMPP.DataForms;
using Waher.Networking.XMPP.DataForms.DataTypes;
using Waher.Networking.XMPP.DataForms.FieldTypes;
using Waher.Networking.XMPP.DataForms.ValidationMethods;
using Waher.Networking.XMPP.Events;
using Waher.Networking.XMPP.ServiceDiscovery;
using Waher.Networking.XMPP.SoftwareVersion;
using Waher.Networking.XMPP.Search;
using Waher.Runtime.Inventory;
using Waher.Security;
namespace Waher.Networking.XMPP
{
/// <summary>
/// Manages an XMPP client connection. Implements XMPP, as defined in
/// https://tools.ietf.org/html/rfc6120
/// https://tools.ietf.org/html/rfc6121
/// https://tools.ietf.org/html/rfc6122
///
/// Extensions supported directly by client object:
///
/// XEP-0030: Service Discovery: http://xmpp.org/extensions/xep-0030.html
/// XEP-0055: Jabber Search: http://xmpp.org/extensions/xep-0055.html
/// XEP-0077: In-band Registration: http://xmpp.org/extensions/xep-0077.html
/// XEP-0092: Software Version: http://xmpp.org/extensions/xep-0092.html
/// XEP-0115: Entity Capabilities: http://xmpp.org/extensions/xep-0115.html
/// XEP-0124: Bidirectional-streams Over Synchronous HTTP (BOSH): https://xmpp.org/extensions/xep-0124.html
/// XEP-0128: Service Discovery Extensions: http://xmpp.org/extensions/xep-0128.html
/// XEP-0199: XMPP Ping: http://xmpp.org/extensions/xep-0199.html
/// XEP-0206: XMPP Over BOSH: https://xmpp.org/extensions/xep-0206.html
///
/// Quality of Service: http://xmpp.org/extensions/inbox/qos.html
/// </summary>
public class XmppClient : CommunicationLayer, IDisposableAsync, IHostReference
{
/// <summary>
/// http://etherx.jabber.org/streams
/// </summary>
public const string NamespaceStream = "http://etherx.jabber.org/streams";
/// <summary>
/// jabber:client
/// </summary>
public const string NamespaceClient = "jabber:client";
/// <summary>
/// urn:ietf:params:xml:ns:xmpp-streams
/// </summary>
public const string NamespaceXmppStreams = "urn:ietf:params:xml:ns:xmpp-streams";
/// <summary>
/// urn:ietf:params:xml:ns:xmpp-stanzas
/// </summary>
public const string NamespaceXmppStanzas = "urn:ietf:params:xml:ns:xmpp-stanzas";
/// <summary>
/// urn:ietf:params:xml:ns:xmpp-sasl
/// </summary>
public const string NamespaceXmppSasl = "urn:ietf:params:xml:ns:xmpp-sasl";
/// <summary>
/// jabber:iq:register
/// </summary>
public const string NamespaceRegister = "jabber:iq:register";
/// <summary>
/// jabber:x:data
/// </summary>
public const string NamespaceData = "jabber:x:data";
/// <summary>
/// http://jabber.org/protocol/xdata-validate
/// </summary>
public const string NamespaceDataValidate = "http://jabber.org/protocol/xdata-validate";
/// <summary>
/// http://jabber.org/protocol/xdata-layout
/// </summary>
public const string NamespaceDataLayout = "http://jabber.org/protocol/xdata-layout";
/// <summary>
/// jabber:iq:roster
/// </summary>
public const string NamespaceRoster = "jabber:iq:roster";
/// <summary>
/// urn:xmpp:xdata:dynamic
/// </summary>
public const string NamespaceDynamicForms = "urn:xmpp:xdata:dynamic";
/// <summary>
/// http://jabber.org/protocol/disco#info
/// </summary>
public const string NamespaceServiceDiscoveryInfo = "http://jabber.org/protocol/disco#info";
/// <summary>
/// http://jabber.org/protocol/disco#items
/// </summary>
public const string NamespaceServiceDiscoveryItems = "http://jabber.org/protocol/disco#items";
/// <summary>
/// jabber:iq:version
/// </summary>
public const string NamespaceSoftwareVersion = "jabber:iq:version";
/// <summary>
/// jabber:iq:search
/// </summary>
public const string NamespaceSearch = "jabber:iq:search";
/// <summary>
/// urn:ieee:iot:qos:1.0
/// </summary>
public const string NamespaceQualityOfServiceIeeeV1 = "urn:ieee:iot:qos:1.0";
/// <summary>
/// urn:nf:iot:qos:1.0
/// </summary>
public const string NamespaceQualityOfServiceNeuroFoundationV1 = "urn:nf:iot:qos:1.0";
/// <summary>
/// Current namespace for Quality of Service.
/// </summary>
public const string NamespaceQualityOfServiceCurrent = NamespaceQualityOfServiceNeuroFoundationV1;
/// <summary>
/// urn:xmpp:ping
/// </summary>
public const string NamespacePing = "urn:xmpp:ping";
/// <summary>
/// http://jabber.org/protocol/caps
/// </summary>
public const string NamespaceEntityCapabilities = "http://jabber.org/protocol/caps";
/// <summary>
/// urn:xmpp:receipts
/// </summary>
public const string NamespaceMessageDeliveryReceipts = "urn:xmpp:receipts";
/// <summary>
/// jabber:iq:private (XEP-0049)
/// </summary>
public const string NamespacePrivateXmlStorage = "jabber:iq:private";
/// <summary>
/// http://waher.se/Schema/QL.xsd
/// </summary>
public const string NamespaceQuickLogin = "http://waher.se/Schema/QL.xsd";
/// <summary>
/// http://waher.se/Schema/AlternativeNames.xsd
/// </summary>
public const string AlternativesNamespace = "http://waher.se/Schema/Alternatives.xsd";
/// <summary>
/// Regular expression for Full JIDs
/// </summary>
public static readonly Regex FullJidRegEx = new Regex("^(?:([^@/<>'\\\"\\s]+)@)([^@/<>'\\\"\\s]+)(?:/([^<>'\\\"\\s]*))?$", RegexOptions.Singleline | RegexOptions.Compiled);
/// <summary>
/// Regular expression for Bare JIDs
/// </summary>
public static readonly Regex BareJidRegEx = new Regex("^(?:([^@/<>'\\\"\\s]+)@)([^@/<>'\\\"\\s]+)$", RegexOptions.Singleline | RegexOptions.Compiled);
/// <summary>
/// Regular expression for Domain JIDs
/// </summary>
public static readonly Regex DomainJidRegEx = new Regex("^(?:([^@/<>'\\\"\\s]+))$", RegexOptions.Singleline | RegexOptions.Compiled);
private readonly static RandomNumberGenerator rnd = RandomNumberGenerator.Create();
private static Type[] alternativeBindingMechanisms = null;
private const int KeepAliveTimeSeconds = 30;
private const int MaxFragmentSize = 40000000;
private readonly Dictionary<string, bool> authenticationMechanisms = new Dictionary<string, bool>();
private readonly Dictionary<string, bool> compressionMethods = new Dictionary<string, bool>();
private readonly Dictionary<uint, PendingRequest> pendingRequestsBySeqNr = new Dictionary<uint, PendingRequest>();
private readonly SortedDictionary<DateTime, PendingRequest> pendingRequestsByTimeout = new SortedDictionary<DateTime, PendingRequest>();
private readonly Dictionary<string, EventHandlerAsync<IqEventArgs>> iqGetHandlers = new Dictionary<string, EventHandlerAsync<IqEventArgs>>();
private readonly Dictionary<string, EventHandlerAsync<IqEventArgs>> iqSetHandlers = new Dictionary<string, EventHandlerAsync<IqEventArgs>>();
private readonly Dictionary<string, EventHandlerAsync<MessageEventArgs>> messageHandlers = new Dictionary<string, EventHandlerAsync<MessageEventArgs>>();
private readonly Dictionary<string, EventHandlerAsync<MessageFormEventArgs>> messageFormHandlers = new Dictionary<string, EventHandlerAsync<MessageFormEventArgs>>();
private readonly Dictionary<string, EventHandlerAsync<PresenceEventArgs>> presenceHandlers = new Dictionary<string, EventHandlerAsync<PresenceEventArgs>>();
private readonly Dictionary<string, MessageEventArgs> receivedMessages = new Dictionary<string, MessageEventArgs>();
private readonly SortedDictionary<string, bool> clientFeatures = new SortedDictionary<string, bool>();
private ServiceDiscoveryEventArgs serverFeatures = null;
private ServiceItemsDiscoveryEventArgs serverComponents = null;
private readonly SortedDictionary<string, DataForm> extendedServiceDiscoveryInformation = new SortedDictionary<string, DataForm>();
private readonly Dictionary<string, RosterItem> roster = new Dictionary<string, RosterItem>(StringComparer.CurrentCultureIgnoreCase);
private readonly Dictionary<string, PresenceEventArgs> subscriptionRequests = new Dictionary<string, PresenceEventArgs>(StringComparer.CurrentCultureIgnoreCase);
private readonly Dictionary<string, int> pendingAssuredMessagesPerSource = new Dictionary<string, int>();
private readonly Dictionary<string, object> tags = new Dictionary<string, object>();
private readonly List<IXmppExtension> extensions = new List<IXmppExtension>();
private readonly Dictionary<string, string> services = new Dictionary<string, string>();
private readonly IqResponses responses = new IqResponses(TimeSpan.FromMinutes(1));
private AuthenticationMethod authenticationMethod = null;
#if !WINDOWS_UWP
private readonly X509Certificate clientCertificate = null;
#endif
private TextTcpClient client;
private Timer secondTimer = null;
private DateTime nextPing = DateTime.MaxValue;
private readonly UTF8Encoding encoding = new UTF8Encoding(false, false);
private readonly StringBuilder fragment = new StringBuilder();
private int fragmentLength = 0;
private XmppState state;
private readonly Random gen = new Random();
private readonly object synchObject = new object();
private Availability currentAvailability = Availability.Online;
private KeyValuePair<string, string>[] customPresenceStatus = Array.Empty<KeyValuePair<string, string>>();
private ITextTransportLayer textTransportLayer = null;
private HashFunction entityHashFunction = HashFunction.SHA256;
private string entityNode = "https://github.com/PeterWaher/IoTGateway";
private string clientName;
private string clientVersion;
private string clientOS;
private string host;
private readonly string language;
private string domain;
private string bareJid;
private string fullJid;
private string resource = string.Empty;
private string userName;
private string password;
private string passwordHash;
private string passwordHashMethod;
private string streamId;
private string streamHeader;
private string streamFooter;
private string formSignatureKey;
private string formSignatureSecret;
private string entityCapabilitiesVersion = null;
private double version;
private uint seqnr = 0;
private readonly int port;
private int keepAliveSeconds = KeepAliveTimeSeconds;
private int inputState = 0;
private int inputDepth = 0;
private int defaultRetryTimeout = 15000;
private int defaultNrRetries = 0;
private int defaultMaxRetryTimeout = int.MaxValue;
private int maxAssuredMessagesPendingFromSource = 5;
private int maxAssuredMessagesPendingTotal = 100;
private int nrAssuredMessagesPending = 0;
private bool defaultDropOff = true;
private bool trustServer = false;
private bool canRegister = false;
private bool createSession = false;
private bool hasRegistered = false;
private bool hasRoster = false;
private bool presenceSent = false;
private bool requestRosterOnStartup = true;
private bool allowedToRegister = false;
private bool allowCramMD5 = true;
private bool allowDigestMD5 = true;
private bool allowScramSHA1 = true;
private bool allowScramSHA256 = true;
private bool allowPlain = false;
private bool allowQuickLogin = false;
private readonly bool sendHeartbeats = true;
private bool supportsPing = true;
private bool pingResponse = true;
private bool allowEncryption = true;
private bool sendFromAddress = false;
private bool? checkConnection = null;
private bool openBracketReceived = false;
private bool monitorContactResourcesAlive = true;
private bool upgradeToTls = false;
private bool legacyTls = false;
private bool performingQuickLogin = false;
private bool disposed = false;
#if WINDOWS_UWP
/// <summary>
/// Manages an XMPP client connection over a traditional binary socket connection.
/// </summary>
/// <param name="Host">Host name or IP address of XMPP server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="UserName">User Name</param>
/// <param name="Password">Password</param>
/// <param name="Language">Language Code, according to RFC 5646.</param>
/// <param name="AppAssembly">Application assembly.</param>
/// <param name="Sniffers">Sniffers.</param>
public XmppClient(string Host, int Port, string UserName, string Password, string Language, Assembly AppAssembly,
params ISniffer[] Sniffers)
: base(true, Sniffers)
{
this.host = this.domain = Host;
this.port = Port;
this.userName = UserName;
this.password = Password;
this.passwordHash = string.Empty;
this.passwordHashMethod = string.Empty;
this.language = Language;
this.state = XmppState.Offline;
this.Init(AppAssembly);
}
/// <summary>
/// Manages an XMPP client connection over a traditional binary socket connection.
/// </summary>
/// <param name="Host">Host name or IP address of XMPP server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="UserName">User Name</param>
/// <param name="PasswordHash">Password hash.</param>
/// <param name="PasswordHashMethod">Password hash method.</param>
/// <param name="Language">Language Code, according to RFC 5646.</param>
/// <param name="AppAssembly">Application assembly.</param>
/// <param name="Sniffers">Sniffers.</param>
public XmppClient(string Host, int Port, string UserName, string PasswordHash, string PasswordHashMethod, string Language,
Assembly AppAssembly, params ISniffer[] Sniffers)
: base(true, Sniffers)
{
this.host = this.domain = Host;
this.port = Port;
this.userName = UserName;
this.password = string.IsNullOrEmpty(PasswordHashMethod) ? PasswordHash : string.Empty;
this.passwordHash = string.IsNullOrEmpty(PasswordHashMethod) ? string.Empty : PasswordHash;
this.passwordHashMethod = PasswordHashMethod;
this.language = Language;
this.state = XmppState.Offline;
this.Init(AppAssembly);
}
/// <summary>
/// Manages an XMPP client connection. Connection information is defined in
/// <paramref name="Credentials"/>.
/// </summary>
/// <param name="Credentials">Client credentials.</param>
/// <param name="Language">Language Code, according to RFC 5646.</param>
/// <param name="AppAssembly">Application assembly.</param>
/// <param name="Sniffers">Sniffers.</param>
public XmppClient(XmppCredentials Credentials, string Language, Assembly AppAssembly, params ISniffer[] Sniffers)
: base(true, Sniffers)
#else
/// <summary>
/// Manages an XMPP client connection over a traditional binary socket connection.
/// </summary>
/// <param name="Host">Host name or IP address of XMPP server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="UserName">User Name</param>
/// <param name="Password">Password</param>
/// <param name="Language">Language Code, according to RFC 5646.</param>
/// <param name="AppAssembly">Application assembly.</param>
/// <param name="Sniffers">Sniffers.</param>
public XmppClient(string Host, int Port, string UserName, string Password, string Language, Assembly AppAssembly,
params ISniffer[] Sniffers)
: this(Host, Port, UserName, Password, Language, AppAssembly, (X509Certificate)null, Sniffers)
{
}
/// <summary>
/// Manages an XMPP client connection over a traditional binary socket connection.
/// </summary>
/// <param name="Host">Host name or IP address of XMPP server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="UserName">User Name</param>
/// <param name="Password">Password</param>
/// <param name="Language">Language Code, according to RFC 5646.</param>
/// <param name="AppAssembly">Application assembly.</param>
/// <param name="ClientCertificate">Optional client certificate.</param>
/// <param name="Sniffers">Sniffers.</param>
public XmppClient(string Host, int Port, string UserName, string Password, string Language, Assembly AppAssembly,
X509Certificate ClientCertificate, params ISniffer[] Sniffers)
: base(true, Sniffers)
{
this.host = this.domain = Host;
this.port = Port;
this.userName = UserName;
this.password = Password;
this.passwordHash = string.Empty;
this.passwordHashMethod = string.Empty;
this.language = Language;
this.state = XmppState.Offline;
this.clientCertificate = ClientCertificate;
this.Init(AppAssembly);
}
/// <summary>
/// Manages an XMPP client connection over a traditional binary socket connection.
/// </summary>
/// <param name="Host">Host name or IP address of XMPP server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="UserName">User Name</param>
/// <param name="PasswordHash">Password hash.</param>
/// <param name="PasswordHashMethod">Password hash method.</param>
/// <param name="Language">Language Code, according to RFC 5646.</param>
/// <param name="AppAssembly">Application assembly.</param>
/// <param name="Sniffers">Sniffers.</param>
public XmppClient(string Host, int Port, string UserName, string PasswordHash, string PasswordHashMethod, string Language,
Assembly AppAssembly, params ISniffer[] Sniffers)
: this(Host, Port, UserName, PasswordHash, PasswordHashMethod, Language, AppAssembly, null, Sniffers)
{
}
/// <summary>
/// Manages an XMPP client connection over a traditional binary socket connection.
/// </summary>
/// <param name="Host">Host name or IP address of XMPP server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="UserName">User Name</param>
/// <param name="PasswordHash">Password hash.</param>
/// <param name="PasswordHashMethod">Password hash method.</param>
/// <param name="Language">Language Code, according to RFC 5646.</param>
/// <param name="AppAssembly">Application assembly.</param>
/// <param name="ClientCertificate">Optional client certificate.</param>
/// <param name="Sniffers">Sniffers.</param>
public XmppClient(string Host, int Port, string UserName, string PasswordHash, string PasswordHashMethod, string Language, Assembly AppAssembly,
X509Certificate ClientCertificate, params ISniffer[] Sniffers)
: base(true, Sniffers)
{
this.host = this.domain = Host;
this.port = Port;
this.userName = UserName;
this.password = string.IsNullOrEmpty(PasswordHashMethod) ? PasswordHash : string.Empty;
this.passwordHash = string.IsNullOrEmpty(PasswordHashMethod) ? string.Empty : PasswordHash;
this.passwordHashMethod = PasswordHashMethod;
this.language = Language;
this.state = XmppState.Offline;
this.clientCertificate = ClientCertificate;
this.Init(AppAssembly);
}
/// <summary>
/// Manages an XMPP client connection. Connection information is defined in
/// <paramref name="Credentials"/>.
/// </summary>
/// <param name="Credentials">Client credentials.</param>
/// <param name="Language">Language Code, according to RFC 5646.</param>
/// <param name="AppAssembly">Application assembly.</param>
/// <param name="Sniffers">Sniffers.</param>
public XmppClient(XmppCredentials Credentials, string Language, Assembly AppAssembly, params ISniffer[] Sniffers)
: base(true, Sniffers)
#endif
{
this.host = this.domain = Credentials.Host;
this.port = Credentials.Port;
this.userName = Credentials.Account;
if (!string.IsNullOrEmpty(Credentials.UriEndpoint))
{
Uri URI = new Uri(Credentials.UriEndpoint);
if (alternativeBindingMechanisms is null)
{
alternativeBindingMechanisms = Types.GetTypesImplementingInterface(typeof(IAlternativeTransport));
Types.OnInvalidated += this.Types_OnInvalidated;
}
IAlternativeTransport Best = Types.FindBest<IAlternativeTransport, Uri>(URI, alternativeBindingMechanisms);
if (!(Best is null))
{
IAlternativeTransport AlternativeTransport = Best.Instantiate(URI, this, new XmppBindingInterface(this));
this.textTransportLayer = AlternativeTransport;
this.textTransportLayer.OnReceived += this.TextTransportLayer_OnReceived_NoSniff;
this.sendHeartbeats = !AlternativeTransport.HandlesHeartbeats;
}
else
throw new ArgumentException("No alternative binding mechanism found that servers the endpoint URI provided.", nameof(Credentials));
}
if (string.IsNullOrEmpty(Credentials.PasswordType))
{
this.password = Credentials.Password;
this.passwordHash = string.Empty;
this.passwordHashMethod = string.Empty;
}
else
{
this.password = string.Empty;
this.passwordHash = Credentials.Password;
this.passwordHashMethod = Credentials.PasswordType;
}
this.language = Language;
this.state = XmppState.Offline;
#if !WINDOWS_UWP
this.clientCertificate = Credentials.ClientCertificate;
#endif
this.Init(AppAssembly);
this.allowCramMD5 = Credentials.AllowCramMD5;
this.allowDigestMD5 = Credentials.AllowDigestMD5;
this.allowPlain = Credentials.AllowPlain;
this.allowScramSHA1 = Credentials.AllowScramSHA1;
this.allowScramSHA256 = Credentials.AllowScramSHA256;
this.allowEncryption = Credentials.AllowEncryption;
this.requestRosterOnStartup = Credentials.RequestRosterOnStartup;
this.trustServer = Credentials.TrustServer;
if (Credentials.AllowRegistration)
this.AllowRegistration(Credentials.FormSignatureKey, Credentials.FormSignatureSecret);
}
private void Types_OnInvalidated(object Sender, EventArgs e)
{
alternativeBindingMechanisms = Types.GetTypesImplementingInterface(typeof(IAlternativeTransport));
}
private void Init(Assembly Assembly)
{
AssemblyName Name = Assembly.GetName();
string Title = string.Empty;
string Product = string.Empty;
string AssemblyName = Name.Name;
foreach (object Attribute in Assembly.GetCustomAttributes())
{
if (Attribute is AssemblyTitleAttribute AssemblyTitleAttribute)
Title = AssemblyTitleAttribute.Title;
else if (Attribute is AssemblyProductAttribute AssemblyProductAttribute)
Product = AssemblyProductAttribute.Product;
}
if (!string.IsNullOrEmpty(Title))
this.clientName = Title;
else if (!string.IsNullOrEmpty(Product))
this.clientName = Product;
else
this.clientName = AssemblyName;
this.clientVersion = Name.Version.ToString();
this.bareJid = this.fullJid = this.userName + "@" + this.Domain;
/* Alternative for UWP:
string DeviceFamily = Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily;
string DeviceFamilyVersion = Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamilyVersion;
ulong Version = ulong.Parse(DeviceFamilyVersion);
ulong Major = (Version & 0xFFFF000000000000L) >> 48;
ulong Minor = (Version & 0x0000FFFF00000000L) >> 32;
ulong Build = (Version & 0x00000000FFFF0000L) >> 16;
ulong Revision = (Version & 0x000000000000FFFFL);
this.clientOS = DeviceFamily + " " + Major.ToString() + "." + Minor.ToString() + "." + Build.ToString() + "." + Revision.ToString();*/
#if NETFW
this.clientOS = System.Environment.OSVersion.ToString();
#else
this.clientOS = System.Runtime.InteropServices.RuntimeInformation.OSDescription;
#endif
this.RegisterDefaultHandlers();
}
/// <summary>
/// Manages an XMPP client connection. Transport layer is implemented in
/// <paramref name="TextTransporLayer"/>.
/// </summary>
/// <param name="TextTransporLayer">Text transport layer to send and receive XMPP fragments on. The transport layer
/// MUST ALREADY be connected and at least the stream element processed, if applicable. The transport layer is responsible
/// for authenticating incoming requests. Text packets received MUST be complete XML fragments.</param>
/// <param name="State">XMPP state.</param>
/// <param name="StreamHeader">Stream header start tag.</param>
/// <param name="StreamFooter">Stream footer end tag.</param>
/// <param name="BareJid">Bare JID of connection.</param>
/// <param name="AppAssembly">Application assembly.</param>
/// <param name="Sniffers">Sniffers</param>
public XmppClient(ITextTransportLayer TextTransporLayer, XmppState State, string StreamHeader, string StreamFooter, string BareJid,
Assembly AppAssembly, params ISniffer[] Sniffers)
: base(true, Sniffers)
{
this.textTransportLayer = TextTransporLayer;
this.Init(AppAssembly);
this.state = State;
this.pingResponse = true;
this.streamHeader = StreamHeader;
this.streamFooter = StreamFooter;
this.bareJid = this.fullJid = BareJid;
this.ResetState(false, true);
this.textTransportLayer.OnReceived += this.TextTransportLayer_OnReceived;
this.textTransportLayer.OnSent += this.TextTransportLayer_OnSent;
}
private Task<bool> TextTransportLayer_OnSent(object _, string Packet)
{
this.TransmitText(Packet);
return Task.FromResult(true);
}
private Task<bool> TextTransportLayer_OnReceived(object _, string Packet)
{
if (this.openBracketReceived)
{
this.openBracketReceived = false;
this.ReceiveText("<" + Packet);
}
else if (Packet == "<")
this.openBracketReceived = true;
else
this.ReceiveText(Packet);
return this.ProcessFragment(Packet);
}
private async Task<bool> TextTransportLayer_OnReceived_NoSniff(object _, string Packet)
{
if (Packet.StartsWith("</"))
{
await this.ToError();
return false;
}
else
return await this.ProcessFragment(Packet);
}
/// <summary>
/// Connects the client.
/// </summary>
public Task Connect()
{
return this.Connect(this.host);
}
/// <summary>
/// Connects the client.
/// </summary>
/// <param name="Domain">Domain name, if different from the host name provided in the constructor.</param>
public async Task Connect(string Domain)
{
try
{
if (this.disposed)
throw new ObjectDisposedException("XMPP Client has been disposed.");
await this.DisposeClient(false);
this.domain = Domain;
this.bareJid = this.fullJid = this.userName + "@" + Domain;
if (!this.checkConnection.HasValue)
this.checkConnection = true;
this.openBracketReceived = false;
await this.SetState(XmppState.Connecting);
this.pingResponse = true;
this.nextPing = DateTime.Now.AddMilliseconds(this.keepAliveSeconds * 500);
this.serverFeatures = null;
this.serverComponents = null;
this.fragmentLength = 0;
this.fragment.Clear();
this.upgradeToTls = false;
this.performingQuickLogin = false;
lock (this.synchObject)
{
this.services.Clear();
}
if (this.textTransportLayer is null)
{
this.client = new TextTcpClient(this.encoding, true);
this.client.OnReceived += this.OnReceived;
this.client.OnSent += this.OnSent;
this.client.OnError += this.Error;
this.client.OnDisconnected += this.Client_OnDisconnected;
this.client.OnPaused += this.Client_OnPaused;
if (await this.client.ConnectAsync(this.host, this.port, this.legacyTls))
{
if (this.legacyTls)
{
await this.SetState(XmppState.StartingEncryption);
#if WINDOWS_UWP
await this.client.UpgradeToTlsAsClient(SocketProtectionLevel.Tls12, this.trustServer);
#else
await this.client.UpgradeToTlsAsClient(this.clientCertificate, Crypto.SecureTls, this.trustServer, "xmpp-client");
#endif
this.upgradeToTls = false;
this.client.Continue();
}
await this.SetState(XmppState.StreamNegotiation);
await this.BeginWrite("<?xml version='1.0' encoding='utf-8'?><stream:stream to='" + XML.Encode(this.domain) + "' version='1.0' xml:lang='" +
XML.Encode(this.language) + "' xmlns='" + NamespaceClient + "' xmlns:stream='" +
NamespaceStream + "'>", null, null);
}
else
{
await this.ConnectionError(new Exception("Unable to connect to " + this.host + ":" + this.port.ToString()));
return;
}
}
else if (this.textTransportLayer is AlternativeTransport AlternativeTransport)
{
await this.SetState(XmppState.StreamNegotiation);
AlternativeTransport.CreateSession();
}
this.ResetState(false, true);
}
catch (Exception ex)
{
await this.ConnectionError(ex);
}
}
private async Task Client_OnDisconnected(object Sender, EventArgs e)
{
this.Information("Disconnected.");
if (this.state != XmppState.Error)
await this.SetState(XmppState.Offline);
}
private Task<bool> OnSent(object _, string Text)
{
this.TransmitText(Text);
return Task.FromResult(true);
}
private Task<bool> OnReceived(object _, string Text)
{
if (this.openBracketReceived)
{
this.openBracketReceived = false;
this.ReceiveText("<" + Text);
}
else if (Text == "<")
this.openBracketReceived = true;
else
this.ReceiveText(Text);
return this.ParseIncoming(Text);
}
private void RegisterDefaultHandlers()
{
this.RegisterIqSetHandler("query", NamespaceRoster, this.RosterPushHandler, true);
this.RegisterIqGetHandler("query", NamespaceServiceDiscoveryInfo, this.ServiceDiscoveryRequestHandler, true);
this.RegisterIqGetHandler("query", NamespaceSoftwareVersion, this.SoftwareVersionRequestHandler, true);
this.RegisterIqGetHandler("ping", NamespacePing, this.PingRequestHandler, true);
#region Neuro-Foundation V1
this.RegisterIqSetHandler("acknowledged", NamespaceQualityOfServiceNeuroFoundationV1, this.AcknowledgedQoSMessageHandler, true);
this.RegisterIqSetHandler("assured", NamespaceQualityOfServiceNeuroFoundationV1, this.AssuredQoSMessageHandler, false);
this.RegisterIqSetHandler("deliver", NamespaceQualityOfServiceNeuroFoundationV1, this.DeliverQoSMessageHandler, false);
#endregion
#region IEEE V1
this.RegisterIqSetHandler("acknowledged", NamespaceQualityOfServiceIeeeV1, this.AcknowledgedQoSMessageHandler, true);
this.RegisterIqSetHandler("assured", NamespaceQualityOfServiceIeeeV1, this.AssuredQoSMessageHandler, false);
this.RegisterIqSetHandler("deliver", NamespaceQualityOfServiceIeeeV1, this.DeliverQoSMessageHandler, false);
#endregion
this.RegisterMessageHandler("updated", NamespaceDynamicForms, this.DynamicFormUpdatedHandler, true);
this.clientFeatures[NamespaceMessageDeliveryReceipts] = true;
this.clientFeatures["urn:xmpp:xdata:signature:oauth1"] = true;
this.clientFeatures["http://jabber.org/protocols/xdata-validate"] = true;
this.clientFeatures[NamespaceData] = true;
this.clientFeatures[NamespaceEntityCapabilities] = true;
this.entityCapabilitiesVersion = null;
}
private void ResetState(bool Authenticated, bool ExpectStream)
{
if (ExpectStream)
{
this.inputState = 0;
this.inputDepth = 0;
this.performingQuickLogin = false;
this.canRegister = false;
this.presenceSent = false;
if (!Authenticated)
{
this.authenticationMethod = null;
this.authenticationMechanisms.Clear();
}
this.compressionMethods.Clear();
}
else
{
this.inputState = 5;
this.inputDepth = 1;
}
lock (this.synchObject)
{
this.pendingRequestsBySeqNr.Clear();
this.pendingRequestsByTimeout.Clear();
}
this.responses.Clear();
}
internal async Task ConnectionError(Exception ex)
{
await this.SetState(XmppState.Error);
await this.OnConnectionError.Raise(this, ex);
await this.Error(this, ex);
this.inputState = -1;
await this.DisposeClient(false);
}
private async Task Error(object _, Exception Exception)
{
await this.SetState(XmppState.Error);
Exception = Log.UnnestException(Exception);
if (Exception is AggregateException ex)
{
foreach (Exception ex2 in ex.InnerExceptions)
await this.Error(this, ex2);
}
else
{
this.Exception(Exception);
await this.OnError.Raise(this, Exception);
}
}
/// <summary>
/// Event raised when a connection to a broker could not be made.
/// </summary>
public event EventHandlerAsync<Exception> OnConnectionError = null;
/// <summary>
/// Event raised when an error was encountered.
/// </summary>
public event EventHandlerAsync<Exception> OnError = null;
/// <summary>
/// Host or IP address of XMPP server.
/// </summary>
public string Host => this.host;
/// <summary>
/// Port number to connect to.
/// </summary>
public int Port => this.port;
/// <summary>
/// Underlying text transport layer, if such was provided to create the XMPP client.
/// </summary>
public ITextTransportLayer TextTransportLayer => this.textTransportLayer;
internal string StreamHeader
{
get => this.streamHeader;
set => this.streamHeader = value;
}
internal string StreamFooter
{
get => this.streamFooter;
set => this.streamFooter = value;
}
internal DateTime NextPing
{
get => this.nextPing;
set => this.nextPing = value;
}
/// <summary>
/// If server should be trusted, regardless if the operating system could validate its certificate or not.
/// </summary>
public bool TrustServer
{
get => this.trustServer;
set => this.trustServer = value;
}
/// <summary>
/// Legacy TLS means TLS negotiation is done directly after connection.
/// By default, this is false, and TLS is negotiated using STARTTLS.
/// </summary>
public bool LegacyTls
{
get => this.legacyTls;
set => this.legacyTls = value;
}
/// <summary>
/// Certificate used by the server.
/// </summary>
#if WINDOWS_UWP
public Certificate ServerCertificate
#else
public X509Certificate ServerCertificate
#endif
=> this.client.RemoteCertificate;
/// <summary>
/// If the server certificate is valid.
/// </summary>
public bool ServerCertificateValid => this.client.RemoteCertificateValid;
/// <summary>
/// Name of the client in the XMPP network.
/// </summary>
public string ClientName => this.clientName;
/// <summary>
/// Version of the client in the XMPP network.
/// </summary>
public string ClientVersion => this.clientVersion;
/// <summary>
/// OS of the client in the XMPP network.
/// </summary>
public string ClientOS => this.clientOS;
/// <summary>
/// Language of the client in the XMPP network.
/// </summary>
public string Language => this.language;
/// <summary>
/// Monitors contact resources to see they are alive.
/// </summary>
public bool MonitorContactResourcesAlive
{
get => this.monitorContactResourcesAlive;
set => this.monitorContactResourcesAlive = value;
}
/// <summary>
/// Last availability set by the client when setting presence.
/// </summary>
public Availability LastSetPresenceAvailability => this.currentAvailability;
/// <summary>
/// Last custom status set by the client when setting presence.
/// </summary>
public KeyValuePair<string, string>[] LastSetPresenceCustomStatus => this.customPresenceStatus;
/// <summary>
/// If the connection should be regularly checked, and automatic reconnection attempts should be made.
/// This feature is turned on by default, when connecting the client for the first time. If set to false,
/// it must be set to true again, for ping and other connection checks to be made regularly.
/// </summary>
public bool? CheckConnection
{
get => this.checkConnection;
set => this.checkConnection = value;
}
/// <summary>
/// Current state of connection.
/// </summary>
public XmppState State => this.state;
/// <summary>
/// Sets the current state of the connection.
/// </summary>
/// <param name="NewState"></param>
internal async Task SetState(XmppState NewState)
{
if (this.state != NewState)
{
this.state = NewState;
this.Information("State changed to " + NewState.ToString());
await this.RaiseOnStateChanged(NewState);
if (NewState == XmppState.Offline || NewState == XmppState.Error)
{
RosterItem[] Roster = this.Roster;