Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
LegalIdentityGetter.cs
1using System;
2using System.Collections.Generic;
3using System.Collections.Specialized;
4using System.Runtime.ExceptionServices;
5using System.Security.Cryptography.X509Certificates;
6using System.Text;
7using System.Threading.Tasks;
8using System.Web;
9using Waher.Content;
15
17{
21 public class LegalIdentityGetter : IContentGetter, IDisposable
22 {
23 private static string defaultPurpose = string.Empty;
24 private static int defaultTimeoutMilliseconds = 60000;
25
26 private readonly Dictionary<string, TaskCompletionSource<LegalIdentityPetitionResponseEventArgs>> identityPetitions = new Dictionary<string, TaskCompletionSource<LegalIdentityPetitionResponseEventArgs>>();
27 private readonly object syncObj = new object();
28 private bool handlerAdded = false;
29
34 {
35 }
36
40 public static string DefaultPurpose
41 {
42 get => defaultPurpose;
43 set
44 {
45 if (string.IsNullOrEmpty(value))
46 throw new ArgumentException("Default purpose cannot be empty.", nameof(DefaultPurpose));
47
48 defaultPurpose = value;
49 }
50 }
51
56 {
57 get => defaultTimeoutMilliseconds;
58 set
59 {
60 if (value <= 0)
61 throw new ArgumentException("Default timeout must be positivt.", nameof(DefaultTimeoutMilliseconds));
62
63 defaultTimeoutMilliseconds = value;
64 }
65 }
66
70 public string[] UriSchemes => new string[] { "iotid" };
71
78 public bool CanGet(Uri Uri, out Grade Grade)
79 {
80 if (string.Compare(Uri.Scheme, "iotid", true) == 0)
81 {
82 Grade = Grade.Ok;
83 return true;
84 }
85 else
86 {
87 Grade = Grade.NotAtAll;
88 return false;
89 }
90 }
91
95 public void Dispose()
96 {
97 lock (this.syncObj)
98 {
99 if (this.handlerAdded)
100 {
101 Gateway.ContractsClient.PetitionedIdentityResponseReceived -= this.Client_PetitionedIdentityResponseReceived;
102 this.handlerAdded = false;
103 }
104 }
105 }
106
115 public Task<object> GetAsync(Uri Uri, X509Certificate Certificate, RemoteCertificateEventHandler RemoteCertificateValidator,
116 params KeyValuePair<string, string>[] Headers)
117 {
118 return this.GetAsync(Uri, Certificate, RemoteCertificateValidator, defaultTimeoutMilliseconds, Headers);
119 }
120
130 public async Task<object> GetAsync(Uri Uri, X509Certificate Certificate, RemoteCertificateEventHandler RemoteCertificateValidator,
131 int TimeoutMs, params KeyValuePair<string, string>[] Headers)
132 {
133 ContractsClient Client = Gateway.ContractsClient
134 ?? throw new NotSupportedException("Contracts feature not supported or activated on this system.");
135
136 lock (this.syncObj)
137 {
138 if (!this.handlerAdded)
139 {
140 Client.PetitionedIdentityResponseReceived += this.Client_PetitionedIdentityResponseReceived;
141 this.handlerAdded = true;
142 }
143 }
144
145 string LegalId = Uri.AbsolutePath;
146
147 try
148 {
149 return await Client.GetLegalIdentityAsync(LegalId);
150 }
151 catch (Exception)
152 {
153 TaskCompletionSource<LegalIdentityPetitionResponseEventArgs> Result = new TaskCompletionSource<LegalIdentityPetitionResponseEventArgs>();
154 string PetitionId = Guid.NewGuid().ToString();
155 string Purpose = null;
156
157 if (!string.IsNullOrEmpty(Uri.Query))
158 {
159 NameValueCollection Parameters = HttpUtility.ParseQueryString(Uri.Query);
160
161 foreach (string Parameter in Parameters.AllKeys)
162 {
163 switch (Parameter.ToLower())
164 {
165 case "p":
166 case "purpose":
167 Purpose = Parameters[Parameter];
168 break;
169 }
170 }
171 }
172
173 if (string.IsNullOrEmpty(Purpose))
174 Purpose = "Processing referenced identity.";
175
176 lock (this.syncObj)
177 {
178 this.identityPetitions[PetitionId] = Result;
179 }
180
181 try
182 {
183 await Client.PetitionIdentityAsync(LegalId, PetitionId, Purpose);
184
185 Task _ = Task.Delay(TimeoutMs).ContinueWith((T) =>
186 {
187 Result.TrySetException(new TimeoutException("Response to petition not received within allotted time."));
188 return Task.CompletedTask;
189 });
190 }
191 catch (Exception ex)
192 {
193 lock (this.syncObj)
194 {
195 this.identityPetitions.Remove(PetitionId);
196 }
197
198 ExceptionDispatchInfo.Capture(ex).Throw();
199 }
200
201 LegalIdentityPetitionResponseEventArgs e = await Result.Task;
202
203 return e.RequestedIdentity;
204 }
205 }
206
207 private Task Client_PetitionedIdentityResponseReceived(object Sender, LegalIdentityPetitionResponseEventArgs e)
208 {
209 lock (this.syncObj)
210 {
211 if (this.identityPetitions.TryGetValue(e.PetitionId, out TaskCompletionSource<LegalIdentityPetitionResponseEventArgs> Result))
212 Result.TrySetResult(e);
213 }
214
215 return Task.CompletedTask;
216 }
217
226 public Task<KeyValuePair<string, TemporaryStream>> GetTempStreamAsync(Uri Uri, X509Certificate Certificate,
227 RemoteCertificateEventHandler RemoteCertificateValidator, params KeyValuePair<string, string>[] Headers)
228 {
229 return this.GetTempStreamAsync(Uri, Certificate, RemoteCertificateValidator, defaultTimeoutMilliseconds, Headers);
230 }
231
241 public async Task<KeyValuePair<string, TemporaryStream>> GetTempStreamAsync(Uri Uri, X509Certificate Certificate,
242 RemoteCertificateEventHandler RemoteCertificateValidator, int TimeoutMs, params KeyValuePair<string, string>[] Headers)
243 {
244 LegalIdentity Identity = (LegalIdentity)await this.GetAsync(Uri, Certificate, RemoteCertificateValidator, TimeoutMs, Headers);
245 StringBuilder Xml = new StringBuilder();
246 Identity.Serialize(Xml, true, true, true, true, true, true, true);
247 byte[] Bin = Encoding.UTF8.GetBytes(Xml.ToString());
248
249 TemporaryStream Result = new TemporaryStream();
250 try
251 {
252 await Result.WriteAsync(Bin, 0, Bin.Length);
253 }
254 catch (Exception ex)
255 {
256 Result.Dispose();
257 ExceptionDispatchInfo.Capture(ex).Throw();
258 Result = null;
259 }
260
261 return new KeyValuePair<string, TemporaryStream>("application/xml; charset=utf-8", Result);
262 }
263 }
264}
Adds support for legal identities, smart contracts and signatures to an XMPP client.
Task PetitionIdentityAsync(string LegalId, string PetitionId, string Purpose)
Sends a petition to the owner of a legal identity, to access the information in the identity....
Task< LegalIdentity > GetLegalIdentityAsync(string LegalIdentityId)
Gets legal identity registered with the account.
Abstract base class for contractual parameters
Definition: Parameter.cs:17
Manages a temporary stream. Contents is kept in-memory, if below a memory threshold,...
override void Dispose(bool disposing)
Releases the unmanaged resources used by the System.IO.Stream and optionally releases the managed res...
override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
Asynchronously writes a sequence of bytes to the current stream, advances the current position within...
Basic interface for Internet Content getters. A class implementing this interface and having a defaul...
delegate void RemoteCertificateEventHandler(object Sender, RemoteCertificateEventArgs e)
Delegate for remote certificate event handlers.
Grade
Grade enumeration
Definition: Grade.cs:7