-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathProvisioningClient.cs
2210 lines (1919 loc) · 89 KB
/
ProvisioningClient.cs
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.Text;
using System.Xml;
using System.Threading.Tasks;
#if WINDOWS_UWP
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Security.Cryptography.Certificates;
using Windows.Storage.Streams;
#else
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
#endif
using Waher.Content;
using Waher.Content.Xml;
using Waher.Events;
using Waher.Networking.XMPP.Events;
using Waher.Networking.XMPP.StanzaErrors;
using Waher.Networking.XMPP.Provisioning.Cache;
using Waher.Networking.XMPP.Provisioning.Events;
using Waher.Networking.XMPP.ServiceDiscovery;
using Waher.Persistence;
using Waher.Persistence.Filters;
using Waher.Things;
using Waher.Things.SensorData;
namespace Waher.Networking.XMPP.Provisioning
{
/// <summary>
/// Implements an XMPP provisioning client interface.
///
/// The interface is defined in the Neuro-Foundation XMPP IoT extensions:
/// https://neuro-foundation.io
/// </summary>
public class ProvisioningClient : XmppExtension
{
private readonly Dictionary<string, CertificateUse> certificates = new Dictionary<string, CertificateUse>();
private readonly string provisioningServerAddress;
private string ownerJid = string.Empty;
private DateTime lastCheck = DateTime.MinValue;
private Duration cacheUnusedLifetime = Duration.FromMonths(13);
private bool managePresenceSubscriptionRequests = true;
/// <summary>
/// urn:ieee:iot:prov:t:1.0
/// </summary>
public const string NamespaceProvisioningTokenIeeeV1 = "urn:ieee:iot:prov:t:1.0";
/// <summary>
/// urn:nf:iot:prov:t:1.0
/// </summary>
public const string NamespaceProvisioningTokenNeuroFoundationV1 = "urn:nf:iot:prov:t:1.0";
/// <summary>
/// Current namespace for provisioning of tokens.
/// </summary>
public const string NamespaceProvisioningTokenCurrent = NamespaceProvisioningTokenNeuroFoundationV1;
/// <summary>
/// Namespaces supported for provisioning tokens.
/// </summary>
public static readonly string[] NamespacesProvisioningToken = new string[]
{
NamespaceProvisioningTokenIeeeV1,
NamespaceProvisioningTokenNeuroFoundationV1
};
/// <summary>
/// urn:ieee:iot:prov:d:1.0
/// </summary>
public const string NamespaceProvisioningDeviceIeeeV1 = "urn:ieee:iot:prov:d:1.0";
/// <summary>
/// urn:nf:iot:prov:d:1.0
/// </summary>
public const string NamespaceProvisioningDeviceNeuroFoundationV1 = "urn:nf:iot:prov:d:1.0";
/// <summary>
/// Current namespace for provisioning of devices.
/// </summary>
public const string NamespaceProvisioningDeviceCurrent = NamespaceProvisioningDeviceNeuroFoundationV1;
/// <summary>
/// Namespaces supported for provisioning devices.
/// </summary>
public static readonly string[] NamespacesProvisioningDevice = new string[]
{
NamespaceProvisioningDeviceIeeeV1,
NamespaceProvisioningDeviceNeuroFoundationV1
};
/// <summary>
/// urn:ieee:iot:prov:o:1.0
/// </summary>
public const string NamespaceProvisioningOwnerIeeeV1 = "urn:ieee:iot:prov:o:1.0";
/// <summary>
/// urn:nf:iot:prov:o:1.0
/// </summary>
public const string NamespaceProvisioningOwnerNeuroFoundationV1 = "urn:nf:iot:prov:o:1.0";
/// <summary>
/// Current namespace for provisioning by owners.
/// </summary>
public const string NamespaceProvisioningOwnerCurrent = NamespaceProvisioningOwnerNeuroFoundationV1;
/// <summary>
/// Namespaces supported for provisioning owners.
/// </summary>
public static readonly string[] NamespacesProvisioningOwner = new string[]
{
NamespaceProvisioningOwnerIeeeV1,
NamespaceProvisioningOwnerNeuroFoundationV1
};
/// <summary>
/// Implements an XMPP provisioning client interface.
///
/// The interface is defined in the Neuro-Foundation XMPP IoT extensions:
/// https://neuro-foundation.io
/// </summary>
/// <param name="Client">XMPP Client</param>
/// <param name="ProvisioningServerAddress">Provisioning Server XMPP Address.</param>
public ProvisioningClient(XmppClient Client, string ProvisioningServerAddress)
: this(Client, ProvisioningServerAddress, string.Empty)
{
}
/// <summary>
/// Implements an XMPP provisioning client interface.
///
/// The interface is defined in the Neuro-Foundation XMPP IoT extensions:
/// https://neuro-foundation.io
/// </summary>
/// <param name="Client">XMPP Client</param>
/// <param name="ProvisioningServerAddress">Provisioning Server XMPP Address.</param>
/// <param name="OwnerJid">JID of owner, if known.</param>
public ProvisioningClient(XmppClient Client, string ProvisioningServerAddress, string OwnerJid)
: base(Client)
{
this.provisioningServerAddress = ProvisioningServerAddress;
this.ownerJid = OwnerJid;
#region Neuro-Foundation V1
this.client.RegisterIqGetHandler("tokenChallenge", NamespaceProvisioningTokenNeuroFoundationV1, this.TokenChallengeHandler, true);
this.client.RegisterIqSetHandler("clearCache", NamespaceProvisioningDeviceNeuroFoundationV1, this.ClearCacheHandler, true);
this.client.RegisterMessageHandler("unfriend", NamespaceProvisioningDeviceNeuroFoundationV1, this.UnfriendHandler, false);
this.client.RegisterMessageHandler("friend", NamespaceProvisioningDeviceNeuroFoundationV1, this.FriendHandler, false);
this.client.RegisterMessageHandler("isFriend", NamespaceProvisioningOwnerNeuroFoundationV1, this.IsFriendHandler, true);
this.client.RegisterMessageHandler("canRead", NamespaceProvisioningOwnerNeuroFoundationV1, this.CanReadHandler, true);
this.client.RegisterMessageHandler("canControl", NamespaceProvisioningOwnerNeuroFoundationV1, this.CanControlHandler, true);
#endregion
#region IEEE V1
this.client.RegisterIqGetHandler("tokenChallenge", NamespaceProvisioningTokenIeeeV1, this.TokenChallengeHandler, true);
this.client.RegisterIqSetHandler("clearCache", NamespaceProvisioningDeviceIeeeV1, this.ClearCacheHandler, true);
this.client.RegisterMessageHandler("unfriend", NamespaceProvisioningDeviceIeeeV1, this.UnfriendHandler, false);
this.client.RegisterMessageHandler("friend", NamespaceProvisioningDeviceIeeeV1, this.FriendHandler, false);
this.client.RegisterMessageHandler("isFriend", NamespaceProvisioningOwnerIeeeV1, this.IsFriendHandler, true);
this.client.RegisterMessageHandler("canRead", NamespaceProvisioningOwnerIeeeV1, this.CanReadHandler, true);
this.client.RegisterMessageHandler("canControl", NamespaceProvisioningOwnerIeeeV1, this.CanControlHandler, true);
#endregion
this.client.OnPresenceSubscribe += this.Client_OnPresenceSubscribe;
this.client.OnPresenceUnsubscribe += this.Client_OnPresenceUnsubscribe;
}
/// <inheritdoc/>
public override void Dispose()
{
base.Dispose();
#region Neuro-Foundation V1
this.client.UnregisterIqGetHandler("tokenChallenge", NamespaceProvisioningTokenNeuroFoundationV1, this.TokenChallengeHandler, true);
this.client.UnregisterIqSetHandler("clearCache", NamespaceProvisioningDeviceNeuroFoundationV1, this.ClearCacheHandler, true);
this.client.UnregisterMessageHandler("unfriend", NamespaceProvisioningDeviceNeuroFoundationV1, this.UnfriendHandler, false);
this.client.UnregisterMessageHandler("friend", NamespaceProvisioningDeviceNeuroFoundationV1, this.FriendHandler, false);
this.client.UnregisterMessageHandler("isFriend", NamespaceProvisioningOwnerNeuroFoundationV1, this.IsFriendHandler, true);
this.client.UnregisterMessageHandler("canRead", NamespaceProvisioningOwnerNeuroFoundationV1, this.CanReadHandler, true);
this.client.UnregisterMessageHandler("canControl", NamespaceProvisioningOwnerNeuroFoundationV1, this.CanControlHandler, true);
#endregion
#region IEEE V1
this.client.UnregisterIqGetHandler("tokenChallenge", NamespaceProvisioningTokenIeeeV1, this.TokenChallengeHandler, true);
this.client.UnregisterIqSetHandler("clearCache", NamespaceProvisioningDeviceIeeeV1, this.ClearCacheHandler, true);
this.client.UnregisterMessageHandler("unfriend", NamespaceProvisioningDeviceIeeeV1, this.UnfriendHandler, false);
this.client.UnregisterMessageHandler("friend", NamespaceProvisioningDeviceIeeeV1, this.FriendHandler, false);
this.client.UnregisterMessageHandler("isFriend", NamespaceProvisioningOwnerIeeeV1, this.IsFriendHandler, true);
this.client.UnregisterMessageHandler("canRead", NamespaceProvisioningOwnerIeeeV1, this.CanReadHandler, true);
this.client.UnregisterMessageHandler("canControl", NamespaceProvisioningOwnerIeeeV1, this.CanControlHandler, true);
#endregion
this.client.OnPresenceSubscribe -= this.Client_OnPresenceSubscribe;
this.client.OnPresenceUnsubscribe -= this.Client_OnPresenceUnsubscribe;
}
/// <summary>
/// Implemented extensions.
/// </summary>
public override string[] Extensions => new string[] { "XEP-0324" };
/// <summary>
/// Provisioning server XMPP address.
/// </summary>
public string ProvisioningServerAddress => this.provisioningServerAddress;
/// <summary>
/// JID of owner, if known or available.
/// </summary>
public string OwnerJid
{
get => this.ownerJid;
internal set => this.ownerJid = value;
}
/// <summary>
/// If presence subscription requests should be managed by the client.
/// </summary>
public bool ManagePresenceSubscriptionRequests
{
get => this.managePresenceSubscriptionRequests;
set => this.managePresenceSubscriptionRequests = value;
}
#region Presence subscriptions
private Task Client_OnPresenceUnsubscribe(object Sender, PresenceEventArgs e)
{
if (this.managePresenceSubscriptionRequests)
return e.Accept();
else
return Task.CompletedTask;
}
private async Task Client_OnPresenceSubscribe(object Sender, PresenceEventArgs e)
{
if (this.managePresenceSubscriptionRequests)
{
if (string.Compare(e.From, this.provisioningServerAddress, true) == 0)
{
Log.Informational("Presence subscription from provisioning server accepted.", this.provisioningServerAddress, this.provisioningServerAddress);
await e.Accept();
}
else if (!string.IsNullOrEmpty(this.ownerJid) && string.Compare(e.From, this.ownerJid, true) == 0)
{
Log.Informational("Presence subscription from owner accepted.", this.ownerJid, this.provisioningServerAddress);
await e.Accept();
}
else
await this.IsFriend(XmppClient.GetBareJID(e.From), this.CheckIfFriendCallback, e);
}
}
private async Task CheckIfFriendCallback(object Sender, IsFriendResponseEventArgs e2)
{
PresenceEventArgs e = (PresenceEventArgs)e2.State;
if (e2.Ok && e2.Friend)
{
Log.Informational("Presence subscription accepted.", e.FromBareJID, this.provisioningServerAddress);
await e.Accept();
RosterItem Item = this.client.GetRosterItem(e.FromBareJID);
if (Item is null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From)
await this.client.RequestPresenceSubscription(e.FromBareJID);
}
else
{
Log.Notice("Presence subscription declined.", e.FromBareJID, this.provisioningServerAddress);
await e.Decline();
}
}
#endregion
#region Tokens
/// <summary>
/// Gets a token for a certicate. This token can be used to identify services, devices or users. The provisioning server will
/// challenge the request, and may choose to challenge it further when it is used, to make sure the sender is the correct holder
/// of the private certificate.
/// </summary>
/// <param name="Certificate">Private certificate. Only the public part will be sent to the provisioning server. But the private
/// part is required in order to be able to respond to challenges sent by the provisioning server.</param>
/// <param name="Callback">Callback method called, when token is available.</param>
/// <param name="State">State object that will be passed on to the callback method.</param>
#if WINDOWS_UWP
public Task GetToken(Certificate Certificate, EventHandlerAsync<TokenEventArgs> Callback, object State)
#else
public Task GetToken(X509Certificate2 Certificate, EventHandlerAsync<TokenEventArgs> Callback, object State)
#endif
{
if (!Certificate.HasPrivateKey)
throw new ArgumentException("Certificate must have private key.", nameof(Certificate));
#if WINDOWS_UWP
IBuffer Buffer = Certificate.GetCertificateBlob();
CryptographicBuffer.CopyToByteArray(Buffer, out byte[] Bin);
string Base64 = Convert.ToBase64String(Bin);
#else
byte[] Bin = Certificate.Export(X509ContentType.Cert);
string Base64 = Convert.ToBase64String(Bin);
#endif
return this.client.SendIqGet(this.provisioningServerAddress, "<getToken xmlns='" + NamespaceProvisioningTokenCurrent + "'>" + Base64 + "</getToken>",
this.GetTokenResponse, new object[] { Certificate, Callback, State });
}
private async Task GetTokenResponse(object Sender, IqResultEventArgs e)
{
object[] P = (object[])e.State;
#if WINDOWS_UWP
Certificate Certificate = (Certificate)P[0];
#else
X509Certificate2 Certificate = (X509Certificate2)P[0];
#endif
XmlElement E = e.FirstElement;
if (e.Ok && !(E is null) && E.LocalName == "getTokenChallenge")
{
int SeqNr = XML.Attribute(E, "seqnr", 0);
string Challenge = E.InnerText;
byte[] Bin = Convert.FromBase64String(Challenge);
#if WINDOWS_UWP
CryptographicKey Key = PersistedKeyProvider.OpenPublicKeyFromCertificate(Certificate,
Certificate.SignatureHashAlgorithmName, CryptographicPadding.RsaPkcs1V15);
IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Bin);
Buffer = CryptographicEngine.Decrypt(Key, Buffer, null);
CryptographicBuffer.CopyToByteArray(Buffer, out Bin);
string Response = Convert.ToBase64String(Bin);
#else
Bin = Certificate.GetRSAPrivateKey().Decrypt(Bin, RSAEncryptionPadding.OaepSHA1);
string Response = Convert.ToBase64String(Bin);
#endif
await this.client.SendIqGet(this.provisioningServerAddress, "<getTokenChallengeResponse xmlns='" + NamespaceProvisioningTokenCurrent + "' seqnr='" +
SeqNr.ToString() + "'>" + Response + "</getTokenChallengeResponse>",
this.GetTokenChallengeResponse, P);
}
}
private async Task GetTokenChallengeResponse(object Sender, IqResultEventArgs e)
{
object[] P = (object[])e.State;
#if WINDOWS_UWP
Certificate Certificate = (Certificate)P[0];
#else
X509Certificate2 Certificate = (X509Certificate2)P[0];
#endif
EventHandlerAsync<TokenEventArgs> Callback = (EventHandlerAsync<TokenEventArgs>)P[1];
object State = P[2];
XmlElement E = e.FirstElement;
string Token;
if (e.Ok && !(E is null) && E.LocalName == "getTokenResponse")
{
Token = XML.Attribute(E, "token");
lock (this.certificates)
{
this.certificates[Token] = new CertificateUse(Token, Certificate);
}
}
else
Token = null;
await Callback.Raise(this, new TokenEventArgs(e, State, Token));
}
/// <summary>
/// Tells the client a token has been used, for instance in a sensor data request or control operation. Tokens must be
/// refreshed when they are used, to make sure the client only responds to challenges of recently used certificates.
/// </summary>
/// <param name="Token">Token</param>
public void TokenUsed(string Token)
{
lock (this.certificates)
{
if (this.certificates.TryGetValue(Token, out CertificateUse Use))
Use.LastUse = DateTime.Now;
}
}
/// <summary>
/// Tells the client a token has been used, for instance in a sensor data request or control operation. Tokens must be
/// refreshed when they are used, to make sure the client only responds to challenges of recently used certificates.
/// </summary>
/// <param name="Token">Token</param>
/// <param name="RemoteJid">Remote JID of entity sending the token.</param>
public void TokenUsed(string Token, string RemoteJid)
{
lock (this.certificates)
{
if (this.certificates.TryGetValue(Token, out CertificateUse Use))
{
Use.LastUse = DateTime.Now;
Use.RemoteCertificateJid = RemoteJid;
}
else
this.certificates[Token] = new CertificateUse(Token, RemoteJid);
}
}
private async Task TokenChallengeHandler(object Sender, IqEventArgs e)
{
XmlElement E = e.Query;
string Token = XML.Attribute(E, "token");
string Challenge = E.InnerText;
CertificateUse Use;
lock (this.certificates)
{
if (!this.certificates.TryGetValue(Token, out Use) || (DateTime.Now - Use.LastUse).TotalMinutes > 1)
throw new ForbiddenException("Token not recognized.", e.IQ);
}
if (!(Use.LocalCertificate is null))
{
byte[] Bin = Convert.FromBase64String(Challenge);
#if WINDOWS_UWP
CryptographicKey Key = PersistedKeyProvider.OpenPublicKeyFromCertificate(Use.LocalCertificate,
Use.LocalCertificate.SignatureHashAlgorithmName, CryptographicPadding.RsaPkcs1V15);
IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Bin);
Buffer = CryptographicEngine.Decrypt(Key, Buffer, null);
CryptographicBuffer.CopyToByteArray(Buffer, out Bin);
string Response = Convert.ToBase64String(Bin);
#else
Bin = Use.LocalCertificate.GetRSAPrivateKey().Decrypt(Bin, RSAEncryptionPadding.OaepSHA1);
string Response = Convert.ToBase64String(Bin);
#endif
await e.IqResult("<tokenChallengeResponse xmlns='" + NamespaceProvisioningTokenCurrent + "'>" + Response + "</tokenChallengeResponse>");
}
else
await this.client.SendIqGet(Use.RemoteCertificateJid, e.Query.OuterXml, this.ForwardedTokenChallengeResponse, e);
}
private async Task ForwardedTokenChallengeResponse(object Sender, IqResultEventArgs e2)
{
IqEventArgs e = (IqEventArgs)e2.State;
if (e2.Ok)
await e.IqResult(e2.FirstElement?.OuterXml ?? string.Empty);
else
await e.IqError(e2.ErrorElement?.OuterXml ?? string.Empty);
}
/// <summary>
/// Gets the certificate the corresponds to a token. This certificate can be used to identify services, devices or users.
/// Tokens are challenged to make sure they correspond to the holder of the private part of the corresponding certificate.
/// </summary>
/// <param name="Token">Token corresponding to the requested certificate.</param>
/// <param name="Callback">Callback method called, when certificate is available.</param>
/// <param name="State">State object that will be passed on to the callback method.</param>
public Task GetCertificate(string Token, EventHandlerAsync<CertificateEventArgs> Callback, object State)
{
string Address = this.provisioningServerAddress;
int i = Token.IndexOf(':');
if (i > 0)
{
Address = Token.Substring(0, i);
Token = Token.Substring(i + 1);
}
return this.client.SendIqGet(Address, "<getCertificate xmlns='" + NamespaceProvisioningTokenCurrent + "'>" +
XML.Encode(Token) + "</getCertificate>", async (Sender, e) =>
{
try
{
byte[] Certificate;
XmlElement E;
if (e.Ok && !((E = e.FirstElement) is null) && E.LocalName == "certificate")
Certificate = Convert.FromBase64String(e.FirstElement.InnerText);
else
{
e.Ok = false;
Certificate = null;
}
CertificateEventArgs e2 = new CertificateEventArgs(e, State, Certificate);
await Callback.Raise(Sender, e2);
}
catch (Exception ex)
{
Log.Exception(ex);
}
}, State);
}
#endregion
#region Device side
/// <summary>
/// Asks the provisioning server if a JID is a friend or not.
/// </summary>
/// <param name="JID">JID</param>
/// <param name="Callback">Method to call when response is received.</param>
/// <param name="State">State object to pass to callback method.</param>
public async Task IsFriend(string JID, EventHandlerAsync<IsFriendResponseEventArgs> Callback, object State)
{
if ((!string.IsNullOrEmpty(this.ownerJid) && string.Compare(JID, this.ownerJid, true) == 0) ||
string.Compare(JID, this.provisioningServerAddress, true) == 0)
{
IqResultEventArgs e0 = new IqResultEventArgs(null, string.Empty, this.client.FullJID, this.provisioningServerAddress, true, State);
IsFriendResponseEventArgs e = new IsFriendResponseEventArgs(e0, State, JID, true);
await Callback.Raise(this.client, e);
}
else
{
await this.CachedIqGet("<isFriend xmlns='" + NamespaceProvisioningDeviceCurrent + "' jid='" +
XML.Encode(JID) + "'/>", this.IsFriendCallback, new object[] { Callback, State });
}
}
private async Task IsFriendCallback(object Sender, IqResultEventArgs e)
{
object[] P = (object[])e.State;
EventHandlerAsync<IsFriendResponseEventArgs> Callback = (EventHandlerAsync<IsFriendResponseEventArgs>)P[0];
object State = P[1];
string JID;
bool Result;
XmlElement E = e.FirstElement;
if (e.Ok && !(E is null) && E.LocalName == "isFriendResponse")
{
JID = XML.Attribute(E, "jid");
Result = XML.Attribute(E, "result", false);
}
else
{
Result = false;
JID = null;
}
await Callback.Raise(this, new IsFriendResponseEventArgs(e, State, JID, Result));
}
private Task UnfriendHandler(object Sender, MessageEventArgs e)
{
if (e.From == this.provisioningServerAddress)
{
string Jid = XML.Attribute(e.Content, "jid");
if (!string.IsNullOrEmpty(Jid))
this.client.RequestPresenceUnsubscription(Jid);
}
return Task.CompletedTask;
}
private Task FriendHandler(object Sender, MessageEventArgs e)
{
if (e.From == this.provisioningServerAddress)
{
string Jid = XML.Attribute(e.Content, "jid");
if (!string.IsNullOrEmpty(Jid))
this.client.RequestPresenceSubscription(Jid);
}
return Task.CompletedTask;
}
private bool Split(string FromBareJid, IEnumerable<IThingReference> Nodes, out IEnumerable<IThingReference> ToCheck,
out IEnumerable<IThingReference> Permitted)
{
if (string.Compare(FromBareJid, this.provisioningServerAddress, true) == 0)
{
ToCheck = null;
Permitted = Nodes;
return true;
}
else if (Nodes is null)
{
ToCheck = null;
Permitted = null;
return !string.IsNullOrEmpty(this.ownerJid) && string.Compare(FromBareJid, this.ownerJid, true) == 0;
}
else
{
LinkedList<IThingReference> ToCheck2 = null;
LinkedList<IThingReference> Permitted2 = null;
string Owner;
bool Safe;
foreach (IThingReference Ref in Nodes)
{
if (Ref is ILifeCycleManagement LifeCycleManagement)
{
Safe = (!LifeCycleManagement.IsProvisioned) ||
(!string.IsNullOrEmpty(Owner = LifeCycleManagement.Owner) && string.Compare(FromBareJid, Owner, true) == 0);
}
else if (string.IsNullOrEmpty(Ref.NodeId) && string.IsNullOrEmpty(Ref.SourceId) && string.IsNullOrEmpty(Ref.Partition))
Safe = string.Compare(FromBareJid, this.ownerJid, true) == 0;
else
Safe = false;
if (Safe)
{
if (Permitted2 is null)
{
ToCheck2 = new LinkedList<IThingReference>();
Permitted2 = new LinkedList<IThingReference>();
foreach (IThingReference Ref2 in Nodes)
{
if (Ref2 == Ref)
break;
ToCheck2.AddLast(Ref2);
}
}
Permitted2.AddLast(Ref);
}
else
ToCheck2?.AddLast(Ref);
}
if (Permitted2 is null)
{
ToCheck = Nodes;
Permitted = null;
return false;
}
else
{
ToCheck = ToCheck2;
Permitted = Permitted2;
return ToCheck2.First is null;
}
}
}
/// <summary>
/// Checks if a readout can be performed.
/// </summary>
/// <param name="RequestFromBareJid">Readout request came from this bare JID.</param>
/// <param name="FieldTypes">Field types requested.</param>
/// <param name="Nodes">Any nodes included in the request.</param>
/// <param name="FieldNames">And field names included in the request. If null, all field names are requested.</param>
/// <param name="ServiceTokens">Any service tokens provided.</param>
/// <param name="DeviceTokens">Any device tokens provided.</param>
/// <param name="UserTokens">Any user tokens provided.</param>
/// <param name="Callback">Method to call when result is received.</param>
/// <param name="State">State object to pass on to the callback method.</param>
public async Task CanRead(string RequestFromBareJid, FieldType FieldTypes, IEnumerable<IThingReference> Nodes, IEnumerable<string> FieldNames,
string[] ServiceTokens, string[] DeviceTokens, string[] UserTokens, EventHandlerAsync<CanReadResponseEventArgs> Callback, object State)
{
if (this.Split(RequestFromBareJid, Nodes, out IEnumerable<IThingReference> ToCheck, out IEnumerable<IThingReference> Permitted))
{
IThingReference[] Nodes2 = Permitted as IThingReference[];
if (Nodes2 is null && !(Permitted is null))
{
List<IThingReference> List = new List<IThingReference>();
List.AddRange(Permitted);
Nodes2 = List.ToArray();
}
string[] FieldNames2 = FieldNames as string[];
if (FieldNames2 is null && !(FieldNames is null))
{
List<string> List = new List<string>();
List.AddRange(FieldNames);
FieldNames2 = List.ToArray();
}
IqResultEventArgs e0 = new IqResultEventArgs(null, string.Empty, this.client.FullJID, this.provisioningServerAddress, true, State);
CanReadResponseEventArgs e = new CanReadResponseEventArgs(e0, State, RequestFromBareJid, true, FieldTypes, Nodes2, FieldNames2);
await Callback.Raise(this.client, e);
}
else
{
StringBuilder Xml = new StringBuilder();
Xml.Append("<canRead xmlns='");
Xml.Append(NamespaceProvisioningDeviceCurrent);
Xml.Append("' jid='");
Xml.Append(XML.Encode(RequestFromBareJid));
this.AppendTokens(Xml, "st", ServiceTokens);
this.AppendTokens(Xml, "dt", DeviceTokens);
this.AppendTokens(Xml, "ut", UserTokens);
if ((FieldTypes & FieldType.All) == FieldType.All)
Xml.Append("' all='true");
else
{
if (FieldTypes.HasFlag(FieldType.Momentary))
Xml.Append("' m='true");
if (FieldTypes.HasFlag(FieldType.Peak))
Xml.Append("' p='true");
if (FieldTypes.HasFlag(FieldType.Status))
Xml.Append("' s='true");
if (FieldTypes.HasFlag(FieldType.Computed))
Xml.Append("' c='true");
if (FieldTypes.HasFlag(FieldType.Identity))
Xml.Append("' i='true");
if (FieldTypes.HasFlag(FieldType.Historical))
Xml.Append("' h='true");
}
if (ToCheck is null && FieldNames is null)
Xml.Append("'/>");
else
{
Xml.Append("'>");
if (!(ToCheck is null))
{
foreach (IThingReference Node in ToCheck)
this.AppendNode(Xml, Node);
}
if (!(FieldNames is null))
{
foreach (string FieldName in FieldNames)
{
Xml.Append("<f n='");
Xml.Append(XML.Encode(FieldName));
Xml.Append("'/>");
}
}
Xml.Append("</canRead>");
}
await this.CachedIqGet(Xml.ToString(), async (Sender, e) =>
{
XmlElement E = e.FirstElement;
List<IThingReference> Nodes2 = null;
List<string> Fields2 = null;
FieldType FieldTypes2 = (FieldType)0;
string Jid = string.Empty;
string NodeId;
string SourceId;
string Partition;
bool b;
bool CanRead;
try
{
if (e.Ok && !(E is null) && E.LocalName == "canReadResponse")
{
CanRead = XML.Attribute(E, "result", false);
foreach (XmlAttribute Attr in E.Attributes)
{
switch (Attr.Name)
{
case "jid":
Jid = Attr.Value;
break;
case "all":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes2 |= FieldType.All;
break;
case "h":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes2 |= FieldType.Historical;
break;
case "m":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes2 |= FieldType.Momentary;
break;
case "p":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes2 |= FieldType.Peak;
break;
case "s":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes2 |= FieldType.Status;
break;
case "c":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes2 |= FieldType.Computed;
break;
case "i":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes2 |= FieldType.Identity;
break;
}
}
if (CanRead)
{
if (!(Permitted is null))
Nodes2 = new List<IThingReference>(Permitted);
foreach (XmlNode N in E.ChildNodes)
{
switch (N.LocalName)
{
case "nd":
if (Nodes2 is null)
Nodes2 = new List<IThingReference>();
E = (XmlElement)N;
NodeId = XML.Attribute(E, "id");
SourceId = XML.Attribute(E, "src");
Partition = XML.Attribute(E, "pt");
bool Found = false;
if (!(Nodes is null))
{
foreach (IThingReference Ref in Nodes)
{
if (Ref.NodeId == NodeId && Ref.SourceId == SourceId && Ref.Partition == Partition)
{
Nodes2.Add(Ref);
Found = true;
break;
}
}
}
if (!Found)
Nodes2.Add(new ThingReference(NodeId, SourceId, Partition));
break;
case "f":
if (Fields2 is null)
Fields2 = new List<string>();
Fields2.Add(XML.Attribute((XmlElement)N, "n"));
break;
}
}
}
else if (!(Permitted is null))
{
CanRead = true;
Jid = RequestFromBareJid;
FieldTypes2 = FieldTypes;
Nodes2 = new List<IThingReference>(Permitted);
if (!(FieldNames is null))
Fields2 = new List<string>(FieldNames);
}
}
else
CanRead = false;
}
catch (Exception ex)
{
Log.Exception(ex);
CanRead = false;
}
CanReadResponseEventArgs e2 = new CanReadResponseEventArgs(e, State, Jid, CanRead, FieldTypes2, Nodes2?.ToArray(), Fields2?.ToArray());
await Callback.Raise(this, e2);
}, State);
}
}
private void AppendNode(StringBuilder Xml, IThingReference Node)
{
Xml.Append("<nd");
this.AppendNodeInfo(Xml, Node.NodeId, Node.SourceId, Node.Partition);
Xml.Append("/>");
}
private void AppendNodeInfo(StringBuilder Xml, string NodeId, string SourceId, string Partition)
{
Xml.Append(" id='");
Xml.Append(XML.Encode(NodeId));
if (!string.IsNullOrEmpty(SourceId))
{
Xml.Append("' src='");
Xml.Append(XML.Encode(SourceId));
}
if (!string.IsNullOrEmpty(Partition))
{
Xml.Append("' pt='");
Xml.Append(XML.Encode(Partition));
}
Xml.Append('\'');
}
private void AppendTokens(StringBuilder Xml, string AttributeName, string[] Tokens)
{
if (!(Tokens is null) && Tokens.Length > 0)
{
Xml.Append("' ");
Xml.Append(AttributeName);
Xml.Append("='");
bool First = true;
foreach (string Token in Tokens)
{
if (First)
First = false;
else
Xml.Append(' ');
Xml.Append(Token);
}
}
}
/// <summary>
/// Checks if a control operation can be performed.
/// </summary>
/// <param name="RequestFromBareJid">Readout request came from this bare JID.</param>
/// <param name="Nodes">Any nodes included in the request.</param>
/// <param name="ParameterNames">And parameter names included in the request. If null, all parameter names are requested.</param>
/// <param name="ServiceTokens">Any service tokens provided.</param>
/// <param name="DeviceTokens">Any device tokens provided.</param>
/// <param name="UserTokens">Any user tokens provided.</param>
/// <param name="Callback">Method to call when result is received.</param>
/// <param name="State">State object to pass on to the callback method.</param>
public async Task CanControl(string RequestFromBareJid, IEnumerable<IThingReference> Nodes, IEnumerable<string> ParameterNames,
string[] ServiceTokens, string[] DeviceTokens, string[] UserTokens, EventHandlerAsync<CanControlResponseEventArgs> Callback, object State)
{
if (this.Split(RequestFromBareJid, Nodes, out IEnumerable<IThingReference> ToCheck, out IEnumerable<IThingReference> Permitted))
{
IThingReference[] Nodes2 = Nodes as IThingReference[];
if (Nodes2 is null && !(Nodes is null))
{
List<IThingReference> List = new List<IThingReference>();
List.AddRange(Nodes);
Nodes2 = List.ToArray();
}
string[] ParameterNames2 = ParameterNames as string[];
if (ParameterNames2 is null && !(ParameterNames is null))
{
List<string> List = new List<string>();
List.AddRange(ParameterNames);
ParameterNames2 = List.ToArray();
}
IqResultEventArgs e0 = new IqResultEventArgs(null, string.Empty, this.client.FullJID, this.provisioningServerAddress, true, State);
CanControlResponseEventArgs e = new CanControlResponseEventArgs(e0, State, RequestFromBareJid, true, Nodes2, ParameterNames2);
await Callback.Raise(this.client, e);
}
else
{
StringBuilder Xml = new StringBuilder();
Xml.Append("<canControl xmlns='");
Xml.Append(NamespaceProvisioningDeviceCurrent);
Xml.Append("' jid='");
Xml.Append(XML.Encode(RequestFromBareJid));
this.AppendTokens(Xml, "st", ServiceTokens);
this.AppendTokens(Xml, "dt", DeviceTokens);
this.AppendTokens(Xml, "ut", UserTokens);
if (ToCheck is null && ParameterNames is null)
Xml.Append("'/>");
else
{