-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathXmppComponent.cs
More file actions
2915 lines (2520 loc) · 85.1 KB
/
XmppComponent.cs
File metadata and controls
2915 lines (2520 loc) · 85.1 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.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Threading;
using System.Threading.Tasks;
using Waher.Content;
using Waher.Content.Xml;
using Waher.Events;
using Waher.Networking.XMPP.StanzaErrors;
using Waher.Networking.XMPP.StreamErrors;
using Waher.Runtime.Cache;
using Waher.Networking.Sniffers;
using Waher.Networking.XMPP.Events;
using Waher.Security;
namespace Waher.Networking.XMPP
{
/// <summary>
/// Delegate for event raised to get roster items for the component.
/// </summary>
/// <param name="BareJid">Bare JID</param>
/// <returns>Corresponding roster item, if found, or null, if not found.</returns>
public delegate RosterItem GetRosterItemEventHandler(string BareJid);
/// <summary>
/// Manages an XMPP component connection, as defined in XEP-0114:
/// http://xmpp.org/extensions/xep-0114.html
/// </summary>
public class XmppComponent : CommunicationLayer, IDisposableAsync, IHostReference
{
private const int KeepAliveTimeSeconds = 30;
private const int MaxFragmentSize = 40000000;
private readonly LinkedList<KeyValuePair<string, EventHandler>> outputQueue = new LinkedList<KeyValuePair<string, EventHandler>>();
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, MessageEventArgs> receivedMessages = new Dictionary<string, MessageEventArgs>();
private readonly Dictionary<string, bool> clientFeatures = new Dictionary<string, bool>();
private readonly Dictionary<string, int> pendingAssuredMessagesPerSource = new Dictionary<string, int>();
private readonly IqResponses responses = new IqResponses(TimeSpan.FromMinutes(1));
private Cache<string, uint> pendingPresenceRequests;
private TextTcpClient client = null;
private Timer secondTimer = null;
private DateTime nextPing = DateTime.MinValue;
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 readonly string identityCategory;
private readonly string identityType;
private readonly string identityName;
private string host;
private readonly string componentSubDomain;
private readonly string sharedSecret;
private string streamId;
private string streamHeader;
private string streamFooter;
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 = 5;
private int defaultMaxRetryTimeout = int.MaxValue;
private int maxAssuredMessagesPendingFromSource = 5;
private int maxAssuredMessagesPendingTotal = 100;
private int nrAssuredMessagesPending = 0;
private bool defaultDropOff = true;
private bool supportsPing = true;
private bool pingResponse = true;
private bool openBracketReceived = false;
/// <summary>
/// Manages an XMPP component connection, as defined in XEP-0114:
/// http://xmpp.org/extensions/xep-0114.html
/// </summary>
/// <param name="Host">Host name or IP address of XMPP server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="ComponentSubDomain">Component sub-domain.</param>
/// <param name="SharedSecret">Shared secret for the component.</param>
/// <param name="IdentityCategory">Identity category, as defined in XEP-0030.</param>
/// <param name="IdentityType">Identity type, as defined in XEP-0030.</param>
/// <param name="IdentityName">Identity name, as defined in XEP-0030.</param>
/// <param name="Sniffers">Sniffers</param>
public XmppComponent(string Host, int Port, string ComponentSubDomain, string SharedSecret,
string IdentityCategory, string IdentityType, string IdentityName, params ISniffer[] Sniffers)
: base(true, Sniffers)
{
this.identityCategory = IdentityCategory;
this.identityType = IdentityType;
this.identityName = IdentityName;
this.host = Host;
this.port = Port;
this.componentSubDomain = ComponentSubDomain;
this.sharedSecret = SharedSecret;
this.state = XmppState.Offline;
this.pendingPresenceRequests = new Cache<string, uint>(int.MaxValue, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), true);
this.pendingPresenceRequests.Removed += this.PendingPresenceRequest_Removed;
this.RegisterDefaultHandlers();
this.Connect();
}
private async void Connect()
{
this.State = XmppState.Connecting;
this.pingResponse = true;
this.openBracketReceived = false;
try
{
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;
if (await this.client.ConnectAsync(this.host, this.port))
{
this.State = XmppState.StreamNegotiation;
await this.BeginWrite("<?xml version='1.0' encoding='utf-8'?><stream:stream to='" + XML.Encode(this.componentSubDomain) +
"' xmlns='jabber:component:accept' xmlns:stream='" + XmppClient.NamespaceStream + "'>", null, null);
this.ResetState();
}
else
{
await this.ConnectionError(new System.Exception("Unable to connect to " + this.host + ":" + this.port.ToString()));
return;
}
}
catch (Exception ex)
{
await this.ConnectionError(ex);
}
}
private void RegisterDefaultHandlers()
{
this.RegisterIqGetHandler("query", XmppClient.NamespaceServiceDiscoveryInfo, this.ServiceDiscoveryRequestHandler, true);
this.RegisterIqGetHandler("ping", XmppClient.NamespacePing, this.PingRequestHandler, true);
#region Neuro-Foundation V1
this.RegisterIqSetHandler("acknowledged", XmppClient.NamespaceQualityOfServiceNeuroFoundationV1, this.AcknowledgedQoSMessageHandler, true);
this.RegisterIqSetHandler("assured", XmppClient.NamespaceQualityOfServiceNeuroFoundationV1, this.AssuredQoSMessageHandler, false);
this.RegisterIqSetHandler("deliver", XmppClient.NamespaceQualityOfServiceNeuroFoundationV1, this.DeliverQoSMessageHandler, false);
#endregion
#region IEEE V1
this.RegisterIqSetHandler("acknowledged", XmppClient.NamespaceQualityOfServiceIeeeV1, this.AcknowledgedQoSMessageHandler, true);
this.RegisterIqSetHandler("assured", XmppClient.NamespaceQualityOfServiceIeeeV1, this.AssuredQoSMessageHandler, false);
this.RegisterIqSetHandler("deliver", XmppClient.NamespaceQualityOfServiceIeeeV1, this.DeliverQoSMessageHandler, false);
#endregion
}
private void ResetState()
{
this.inputState = 0;
this.inputDepth = 0;
this.pendingRequestsBySeqNr.Clear();
this.pendingRequestsByTimeout.Clear();
this.responses.Clear();
}
private async Task ConnectionError(Exception ex)
{
await this.OnConnectionError.Raise(this, ex, false);
await this.Error(this, ex);
this.inputState = -1;
await this.DisposeClient();
this.State = XmppState.Error;
}
private Task Client_OnDisconnected(object Sender, EventArgs e)
{
if (this.HasSniffers)
{
try
{
this.Information("Disconnected.");
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
if (this.state != XmppState.Error)
this.State = XmppState.Offline;
return Task.CompletedTask;
}
private async Task Error(object _, Exception ex)
{
this.State = XmppState.Error;
this.Exception(ex);
await this.OnError.Raise(this, ex);
}
private Task<bool> OnSent(object _, string Text)
{
this.TransmitText(Text);
return Task.FromResult(true);
}
private async 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 await this.ParseIncoming(Text);
}
/// <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>
/// Current state of connection.
/// </summary>
public XmppState State
{
get => this.state;
internal set
{
if (this.state != value)
{
this.state = value;
Task.Run(async () =>
{
try
{
this.Information("State changed to " + value.ToString());
await this.RaiseOnStateChanged(value);
}
catch (Exception ex)
{
Log.Exception(ex);
}
});
}
}
}
private Task RaiseOnStateChanged(XmppState State)
{
return this.OnStateChanged.Raise(this, State);
}
/// <summary>
/// Event raised whenever the internal state of the connection changes.
/// </summary>
public event EventHandlerAsync<XmppState> OnStateChanged = null;
/// <summary>
/// Closes the connection and disposes of all resources.
/// </summary>
[Obsolete("Use the DisposeAsync() method.")]
public void Dispose()
{
this.DisposeAsync().Wait();
}
/// <summary>
/// Closes the connection and disposes of all resources.
/// </summary>
public async Task DisposeAsync()
{
if (this.state == XmppState.Connected || this.state == XmppState.FetchingRoster || this.state == XmppState.SettingPresence)
await this.BeginWrite(this.streamFooter, this.CleanUp, null);
else
await this.CleanUp(this, EventArgs.Empty);
}
/// <summary>
/// Closes the connection the hard way. This might disrupt stream processing, but can simulate a lost connection. To close the connection
/// softly, call the <see cref="Dispose"/> method.
///
/// Note: After turning the connection hard-offline, you can reconnect to the server calling the <see cref="Reconnect"/> method.
/// </summary>
public Task HardOffline()
{
return this.CleanUp(this, EventArgs.Empty);
}
private async Task CleanUp(object Sender, EventArgs e)
{
this.State = XmppState.Offline;
this.pendingPresenceRequests?.Dispose();
this.pendingPresenceRequests = null;
if (!(this.outputQueue is null))
{
lock (this.synchObject)
{
this.outputQueue.Clear();
}
}
if (!(this.pendingRequestsBySeqNr is null))
{
lock (this.synchObject)
{
this.pendingRequestsBySeqNr.Clear();
this.pendingRequestsByTimeout.Clear();
}
}
this.secondTimer?.Dispose();
this.secondTimer = null;
await this.DisposeClient();
this.responses.Dispose();
}
private async Task DisposeClient()
{
if (!(this.client is null))
{
await this.client.DisposeAsync();
this.client = null;
}
}
/// <summary>
/// Reconnects a client after an error or if it's offline. Reconnecting, instead of creating a completely new connection,
/// saves time. It binds to the same resource provided earlier, and avoids fetching the roster.
/// </summary>
public async Task Reconnect()
{
await this.DisposeClient();
this.Connect();
}
private async Task BeginWrite(string Xml, EventHandlerAsync<DeliveryEventArgs> Callback, object State)
{
if (string.IsNullOrEmpty(Xml))
{
if (!(Callback is null))
await Callback.Raise(this, new DeliveryEventArgs(State, true));
}
else
{
await this.client.SendAsync(Xml, Callback, State);
this.nextPing = DateTime.Now.AddMilliseconds(this.keepAliveSeconds * 500);
}
}
private async Task<bool> ParseIncoming(string s)
{
bool Result = true;
foreach (char ch in s)
{
switch (this.inputState)
{
case 0: // Waiting for first <
if (ch == '<')
{
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else
this.inputState++;
}
else if (ch > ' ')
{
await this.ToError();
return false;
}
break;
case 1: // Waiting for ? or >
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '?')
this.inputState++;
else if (ch == '>')
{
this.inputState = 5;
this.inputDepth = 1;
await this.ProcessStream(this.fragment.ToString());
this.fragment.Clear();
this.fragmentLength = 0;
}
break;
case 2: // In processing instruction. Waiting for ?>
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '>')
this.inputState++;
break;
case 3: // Waiting for <stream
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '<')
this.inputState++;
else if (ch > ' ')
{
await this.ToError();
return false;
}
break;
case 4: // Waiting for >
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '>')
{
this.inputState++;
this.inputDepth = 1;
await this.ProcessStream(this.fragment.ToString());
this.fragment.Clear();
this.fragmentLength = 0;
}
break;
case 5: // Waiting for start element.
if (ch == '<')
{
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else
this.inputState++;
}
else if (this.inputDepth > 1)
{
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
}
else if (ch > ' ')
{
await this.ToError();
return false;
}
break;
case 6: // Second character in tag
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '/')
this.inputState++;
else if (ch == '!')
this.inputState = 13;
else
this.inputState += 2;
break;
case 7: // Waiting for end of closing tag
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '>')
{
this.inputDepth--;
if (this.inputDepth < 1)
{
await this.ToError();
return false;
}
else
{
if (this.inputDepth == 1)
{
if (!await this.ProcessFragment(this.fragment.ToString()))
Result = false;
this.fragment.Clear();
this.fragmentLength = 0;
}
if (this.inputState > 0)
this.inputState = 5;
}
}
break;
case 8: // Wait for end of start tag
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '>')
{
this.inputDepth++;
this.inputState = 5;
}
else if (ch == '/')
this.inputState++;
else if (ch <= ' ')
this.inputState += 2;
break;
case 9: // Check for end of childless tag.
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '>')
{
if (this.inputDepth == 1)
{
if (!await this.ProcessFragment(this.fragment.ToString()))
Result = false;
this.fragment.Clear();
this.fragmentLength = 0;
}
if (this.inputState != 0)
this.inputState = 5;
}
else
this.inputState--;
break;
case 10: // Check for attributes.
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '>')
{
this.inputDepth++;
this.inputState = 5;
}
else if (ch == '/')
this.inputState--;
else if (ch == '"')
this.inputState++;
else if (ch == '\'')
this.inputState += 2;
break;
case 11: // Double quote attribute.
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '"')
this.inputState--;
break;
case 12: // Single quote attribute.
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '\'')
this.inputState -= 2;
break;
case 13: // Third character in start of comment
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '-')
this.inputState++;
else if (ch == '[')
this.inputState = 18;
else
{
await this.ToError();
return false;
}
break;
case 14: // Fourth character in start of comment
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '-')
this.inputState++;
else
{
await this.ToError();
return false;
}
break;
case 15: // In comment
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '-')
this.inputState++;
break;
case 16: // Second character in end of comment
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '-')
this.inputState++;
else
this.inputState--;
break;
case 17: // Third character in end of comment
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '>')
this.inputState = 5;
else
this.inputState -= 2;
break;
case 18: // Fourth character in start of CDATA
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == 'C')
this.inputState++;
else
{
await this.ToError();
return false;
}
break;
case 19: // Fifth character in start of CDATA
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == 'D')
this.inputState++;
else
{
await this.ToError();
return false;
}
break;
case 20: // Sixth character in start of CDATA
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == 'A')
this.inputState++;
else
{
await this.ToError();
return false;
}
break;
case 21: // Seventh character in start of CDATA
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == 'T')
this.inputState++;
else
{
await this.ToError();
return false;
}
break;
case 22: // Eighth character in start of CDATA
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == 'A')
this.inputState++;
else
{
await this.ToError();
return false;
}
break;
case 23: // Ninth character in start of CDATA
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '[')
this.inputState++;
else
{
await this.ToError();
return false;
}
break;
case 24: // In CDATA
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == ']')
this.inputState++;
break;
case 25: // Second character in end of CDATA
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == ']')
this.inputState++;
else
this.inputState--;
break;
case 26: // Third character in end of CDATA
this.fragment.Append(ch);
if (++this.fragmentLength > MaxFragmentSize)
{
await this.ToError();
return false;
}
else if (ch == '>')
this.inputState = 5;
else if (ch != ']')
this.inputState -= 2;
break;
default:
break;
}
}
return Result;
}
private async Task ToError()
{
this.inputState = -1;
if (!(this.client is null))
{
await this.client.DisposeAsync();
this.client = null;
}
this.State = XmppState.Error;
}
private async Task ProcessStream(string Xml)
{
try
{
int i = Xml.IndexOf("?>");
if (i >= 0)
Xml = Xml.Substring(i + 2).TrimStart();
this.streamHeader = Xml;
i = Xml.IndexOf(":stream");
if (i < 0)
this.streamFooter = "</stream>";
else
this.streamFooter = "</" + Xml.Substring(1, i - 1) + ":stream>";
XmlDocument Doc = XML.ParseXml(Xml + this.streamFooter, true);
if (Doc.DocumentElement.LocalName != "stream")
throw new XmppException("Invalid stream.", Doc.DocumentElement);
XmlElement Stream = Doc.DocumentElement;
this.streamId = XML.Attribute(Stream, "id");
string From = XML.Attribute(Stream, "from");
if (From != this.componentSubDomain)
await this.ConnectionError(new System.Exception("Invalid component address."));
else
{
this.State = XmppState.StreamOpened;
string s = this.streamId + this.sharedSecret;
byte[] Data = System.Text.Encoding.UTF8.GetBytes(s);
await this.BeginWrite("<handshake>" + Hashes.ComputeSHA1HashString(Data) + "</handshake>", null, null);
}
}
catch (Exception ex)
{
await this.ConnectionError(ex);
}
}
private async Task<bool> ProcessFragment(string Xml)
{
XmlDocument Doc;
XmlElement E;
try
{
Doc = XML.ParseXml(this.streamHeader + Xml + this.streamFooter, true);
foreach (XmlNode N in Doc.DocumentElement.ChildNodes)
{
E = N as XmlElement;
if (E is null)
continue;
switch (E.LocalName)
{
case "iq":
string Type = XML.Attribute(E, "type");
string Id = XML.Attribute(E, "id");
string To = XML.Attribute(E, "to");
string From = XML.Attribute(E, "from");
switch (Type)
{
case "get":
if (this.responses.TryGet(From, Id, out string ResponseXml, out bool Ok))
{
if (Ok)
await this.SendIqResult(Id, To, From, ResponseXml);
else
await this.SendIqError(Id, To, From, ResponseXml);
}
else
this.ProcessIq(this.iqGetHandlers, new IqEventArgs(this, E, Id, To, From));
break;
case "set":
if (this.responses.TryGet(From, Id, out ResponseXml, out Ok))
{
if (Ok)
await this.SendIqResult(Id, To, From, ResponseXml);
else
await this.SendIqError(Id, To, From, ResponseXml);
}
else
this.ProcessIq(this.iqSetHandlers, new IqEventArgs(this, E, Id, To, From));
break;
case "result":
case "error":
uint SeqNr;
EventHandlerAsync<IqResultEventArgs> Callback;
object State;
PendingRequest Rec;
Ok = (Type == "result");
if (uint.TryParse(Id, out SeqNr))
{
lock (this.synchObject)
{
if (this.pendingRequestsBySeqNr.TryGetValue(SeqNr, out Rec))
{
Callback = Rec.IqCallback;
State = Rec.State;
this.pendingRequestsBySeqNr.Remove(SeqNr);
this.pendingRequestsByTimeout.Remove(Rec.Timeout);
}
else
{
Callback = null;
State = null;
}
}
await Callback.Raise(this, new IqResultEventArgs(E, Id, To, From, Ok, State));
}
break;
}
break;
case "message":
this.ProcessMessage(new MessageEventArgs(this, E));
break;
case "presence":
this.ProcessPresence(new PresenceEventArgs(this, E));