-
Notifications
You must be signed in to change notification settings - Fork 19
/
Request.cs
470 lines (413 loc) · 14.5 KB
/
Request.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
/*
* Copyright (c) 2011-2015, Longxiang He <helongxiang@smeshlink.com>,
* SmeshLink Technology Co.
*
* Copyright (c) 2019-2020, Jim Schaad <ietf@augustcellars.com>
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY.
*
* This file is part of the CoAP.NET, a CoAP framework in C#.
* Please see README for more information.
*/
using System;
using System.Net;
using System.Text.RegularExpressions;
using Com.AugustCellars.CoAP.Net;
using Com.AugustCellars.CoAP.Observe;
using Com.AugustCellars.CoAP.OSCOAP;
namespace Com.AugustCellars.CoAP
{
/// <summary>
/// This class describes the functionality of a CoAP Request as
/// a subclass of a CoAP Message. It provides:
/// 1. operations to answer a request by a response using respond()
/// 2. different ways to handle incoming responses: receiveResponse() or Respond event
/// </summary>
public class Request : Message
{
private Uri _uri;
private Response _currentResponse;
private IEndPoint _endPoint;
private Object _sync;
/// <summary>
/// Fired when a response arrives.
/// </summary>
public event EventHandler<ResponseEventArgs> Respond;
/// <summary>
/// Occurs when a block of response arrives in a blockwise transfer.
/// </summary>
public event EventHandler<ResponseEventArgs> Responding;
/// <summary>
/// Occurs when a observing request is re-registering.
/// </summary>
public event EventHandler<ReregisterEventArgs> Reregistering;
/// <summary>
/// Initializes a request message.
/// </summary>
public Request(Method method)
: this(method, true)
{ }
/// <summary>
/// Initializes a request message.
/// </summary>
/// <param name="method">The method code of the message</param>
/// <param name="confirmable">True if the request is Confirmable</param>
public Request(Method method, Boolean confirmable)
: base(confirmable ? MessageType.CON : MessageType.NON, (Int32)method)
{
Method = method;
}
/// <summary>
/// Gets the request method.
/// </summary>
public Method Method { get; internal set; }
/// <summary>
/// Gets or sets a value indicating whether this request is a multicast request or not.
/// </summary>
public new bool IsMulticast {
get {
if (Destination == null) {
throw new CoAPException("Must set the destination before we can known");
}
return base.IsMulticast;
}
}
// ReSharper disable once InconsistentNaming
private static readonly Regex regIP = new Regex("(\\[[0-9a-f:]+\\]|[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})", RegexOptions.IgnoreCase);
/// <summary>
/// Gets or sets the URI of this CoAP message.
/// </summary>
// ReSharper disable once InconsistentNaming
public Uri URI
{
get
{
if (_uri == null) {
// M00BUG - The scheme will be wrong in many circumstances!!!!!
UriBuilder ub = new UriBuilder {
Scheme = CoapConstants.UriScheme,
Host = UriHost ?? "localhost",
Port = UriPort,
Path = UriPath,
Query = UriQuery
};
_uri = ub.Uri;
}
return _uri;
}
set
{
if (null != value) {
String host = value.Host;
Int32 port = value.Port;
string scheme = value.Scheme;
if (string.IsNullOrEmpty(scheme)) scheme = CoapConstants.UriScheme;
scheme = scheme.ToLower();
if (string.IsNullOrEmpty(host)) {
throw new CoAPException("Must have a host specified in the URL");
}
// set Uri-Host option if not IP literal
if (!regIP.IsMatch(host)
&& !host.Equals("localhost", StringComparison.OrdinalIgnoreCase)) {
UriHost = host;
}
if (port >= 0) {
if (UriInformation.UriDefaults.ContainsKey(scheme)) {
if (port != UriInformation.UriDefaults[scheme].DefaultPort) {
UriPort = port;
}
}
else {
throw new CoAPException($"Unrecognized or unsupported scheme {scheme}");
}
}
else {
if (UriInformation.UriDefaults.ContainsKey(scheme)) {
port = UriInformation.UriDefaults[scheme].DefaultPort;
}
else {
throw new CoAPException($"Unrecognized or unsupported scheme {scheme}");
}
}
#if NETSTANDARD1_3
Task<IPAddress[]> result = Dns.GetHostAddressesAsync(host);
result.Wait();
Destination = new IPEndPoint(result.Result[0], port);
#else
Destination = new IPEndPoint(Dns.GetHostAddresses(host)[0], port);
#endif
UriPath = value.AbsolutePath;
UriQuery = value.Query;
}
_uri = value;
}
}
/// <summary>
/// Return the endpoint to use for the request
/// </summary>
public IEndPoint EndPoint
{
get => _endPoint ?? (_endPoint = EndPointManager.Default);
set => _endPoint = value;
}
/// <summary>
/// The observe relationship if one exists.
/// </summary>
public CoapObserveRelation ObserveRelation { get; set; }
/// <summary>
/// Gets or sets the response to this request.
/// </summary>
public Response Response
{
get => _currentResponse;
set
{
_currentResponse = value;
if (_sync != null) {
NotifyResponse();
}
FireRespond(value);
}
}
/// <summary>
/// Alias function to set the URI on the request
/// </summary>
/// <param name="uri">URI to send the message to</param>
/// <returns>Current message</returns>
public Request SetUri(String uri)
{
URI = new Uri(uri);
return this;
}
/// <summary>
/// Should we attempt to reconnect to keep an observe relationship fresh
/// in the event the MAX-AGE expires on the current value?
/// </summary>
[Obsolete("Use ObserveRelation.Reconnect instead")]
public bool ObserveReconnect
{
get => ObserveRelation.Reconnect;
set => ObserveRelation.Reconnect = value;
}
/// <summary>
/// Sets CoAP's observe option. If the target resource of this request
/// responds with a success code and also sets the observe option, it will
/// send more responses in the future whenever the resource's state changes.
/// </summary>
/// <returns>Current request</returns>
public Request MarkObserve()
{
Observe = 0;
return this;
}
/// <summary>
/// Sets CoAP's observe option to the value of 1 to proactively cancel.
/// </summary>
/// <returns>Current request</returns>
public Request MarkObserveCancel()
{
Observe = 1;
return this;
}
/// <summary>
/// Gets the value of a query parameter as a <code>String</code>,
/// or <code>null</code> if the parameter does not exist.
/// </summary>
/// <param name="name">a <code>String</code> specifying the name of the parameter</param>
/// <returns>a <code>String</code> representing the single value of the parameter</returns>
public string GetParameter(string name)
{
foreach (Option query in GetOptions(OptionType.UriQuery)) {
string val = query.StringValue;
if (string.IsNullOrEmpty(val)) {
continue;
}
if (val.StartsWith(name + "=")) {
return val.Substring(name.Length + 1);
}
}
return null;
}
#region SendFunctions
/// <summary>
/// Send the request.
/// </summary>
[Obsolete("Call Send() instead. Will be removed in drop 1.7")]
public void Execute()
{
Send();
}
/// <summary>
/// Sends this message.
/// </summary>
public Request Send()
{
ValidateBeforeSending();
EndPoint.SendRequest(this);
return this;
}
/// <summary>
/// Sends the request over the specified endpoint.
/// </summary>
public Request Send(IEndPoint endpoint)
{
ValidateBeforeSending();
_endPoint = endpoint;
endpoint.SendRequest(this);
return this;
}
/// <summary>
/// Wait for a response.
/// </summary>
/// <exception cref="System.Threading.ThreadInterruptedException"></exception>
public Response WaitForResponse()
{
return WaitForResponse(System.Threading.Timeout.Infinite);
}
/// <summary>
/// Wait for a response.
/// </summary>
/// <param name="millisecondsTimeout">the maximum time to wait in milliseconds</param>
/// <returns>the response, or null if timeout occured</returns>
/// <exception cref="System.Threading.ThreadInterruptedException"></exception>
public Response WaitForResponse(Int32 millisecondsTimeout)
{
// lazy initialization of a lock
if (_sync == null) {
lock (this) {
if (_sync == null) {
_sync = new Byte[0];
}
}
}
lock (_sync) {
if (_currentResponse == null &&
!IsCancelled && !IsTimedOut && !IsRejected) {
System.Threading.Monitor.Wait(_sync, millisecondsTimeout);
}
Response resp = _currentResponse;
_currentResponse = null;
return resp;
}
}
#endregion
/// <inheritdoc/>
protected override void OnRejected()
{
if (_sync != null) {
NotifyResponse();
}
base.OnRejected();
}
/// <inheritdoc/>
protected override void OnTimedOut()
{
if (_sync != null) {
NotifyResponse();
}
base.OnTimedOut();
}
/// <inheritdoc/>
protected override void OnCanceled()
{
if (_sync != null) {
NotifyResponse();
}
base.OnCanceled();
}
private void NotifyResponse()
{
lock (_sync) {
System.Threading.Monitor.PulseAll(_sync);
}
}
private void FireRespond(Response response)
{
EventHandler<ResponseEventArgs> h = Respond;
if (h != null) {
h(this, new ResponseEventArgs(response));
}
}
internal void FireResponding(Response response)
{
EventHandler<ResponseEventArgs> h = Responding;
if (h != null) {
h(this, new ResponseEventArgs(response));
}
}
internal void FireReregister(Request refresh)
{
EventHandler<ReregisterEventArgs> h = Reregistering;
if (h != null) {
h(this, new ReregisterEventArgs(refresh));
}
}
private void ValidateBeforeSending()
{
if (Destination == null) {
throw new InvalidOperationException("Missing Destination");
}
if (IsMulticast && this.Type == MessageType.CON) {
throw new InvalidOperationException("Multicast and CON are not compatible.");
}
}
internal override void CopyEventHandler(Message src)
{
base.CopyEventHandler(src);
Request srcReq = src as Request;
if (srcReq != null) {
ForEach(srcReq.Respond, h => Respond += h);
ForEach(srcReq.Responding, h => Responding += h);
}
}
#region Creation Functions
/// <summary>
/// Construct a GET request.
/// </summary>
public static Request NewGet()
{
return new Request(Method.GET);
}
/// <summary>
/// Construct a POST request.
/// </summary>
public static Request NewPost()
{
return new Request(Method.POST);
}
/// <summary>
/// Construct a PUT request.
/// </summary>
public static Request NewPut()
{
return new Request(Method.PUT);
}
/// <summary>
/// Construct a DELETE request.
/// </summary>
public static Request NewDelete()
{
return new Request(Method.DELETE);
}
#endregion
/// <summary>
/// Set the context structure used to OSCORE protect the message
/// </summary>
[ObsoleteAttribute("Use OscoreContext instead")]
public SecurityContext OscoapContext
{
get => OscoreContext;
set => OscoreContext = value;
}
public SecurityContext OscoreContext { get; set; }
/// <summary>
/// Return the security context associated with TLS.
/// </summary>
public ISecureSession TlsContext => (ISecureSession) Session;
/// <summary>
/// Give information about what session the request came from.
/// </summary>
public ISession Session { get; set; }
}
}