This repository was archived by the owner on Jan 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathNancyHost.cs
441 lines (378 loc) · 16.1 KB
/
NancyHost.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
namespace Nancy.Hosting.Self
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading.Tasks;
using Nancy.Bootstrapper;
using Nancy.Extensions;
using Nancy.IO;
using System.Threading;
/// <summary>
/// Allows to host Nancy server inside any application - console or windows service.
/// </summary>
/// <remarks>
/// NancyHost uses <see cref="System.Net.HttpListener"/> internally. Therefore, it requires full .net 4.0 profile (not client profile)
/// to run. <see cref="Start"/> will launch a thread that will listen for requests and then process them. Each request is processed in
/// its own execution thread. NancyHost needs <see cref="SerializableAttribute"/> in order to be used from another appdomain under
/// mono. Working with AppDomains is necessary if you want to unload the dependencies that come with NancyHost.
/// </remarks>
[Serializable]
public class NancyHost : IDisposable
{
private const int ACCESS_DENIED = 5;
private readonly IList<Uri> baseUriList;
private HttpListener listener;
private readonly INancyEngine engine;
private readonly HostConfiguration configuration;
private readonly INancyBootstrapper bootstrapper;
private bool stop = false;
/// <summary>
/// Initializes a new instance of the <see cref="NancyHost"/> class for the specified <paramref name="baseUris"/>.
/// Uses the default configuration
/// </summary>
/// <param name="baseUris">The <see cref="Uri"/>s that the host will listen to.</param>
public NancyHost(params Uri[] baseUris)
: this(NancyBootstrapperLocator.Bootstrapper, new HostConfiguration(), baseUris) { }
/// <summary>
/// Initializes a new instance of the <see cref="NancyHost"/> class for the specified <paramref name="baseUris"/>.
/// Uses the specified configuration.
/// </summary>
/// <param name="baseUris">The <see cref="Uri"/>s that the host will listen to.</param>
/// <param name="configuration">Configuration to use</param>
public NancyHost(HostConfiguration configuration, params Uri[] baseUris)
: this(NancyBootstrapperLocator.Bootstrapper, configuration, baseUris){}
/// <summary>
/// Initializes a new instance of the <see cref="NancyHost"/> class for the specified <paramref name="baseUris"/>, using
/// the provided <paramref name="bootstrapper"/>.
/// Uses the default configuration
/// </summary>
/// <param name="bootstrapper">The bootstrapper that should be used to handle the request.</param>
/// <param name="baseUris">The <see cref="Uri"/>s that the host will listen to.</param>
public NancyHost(INancyBootstrapper bootstrapper, params Uri[] baseUris)
: this(bootstrapper, new HostConfiguration(), baseUris)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NancyHost"/> class for the specified <paramref name="baseUris"/>, using
/// the provided <paramref name="bootstrapper"/>.
/// Uses the specified configuration.
/// </summary>
/// <param name="bootstrapper">The bootstrapper that should be used to handle the request.</param>
/// <param name="configuration">Configuration to use</param>
/// <param name="baseUris">The <see cref="Uri"/>s that the host will listen to.</param>
public NancyHost(INancyBootstrapper bootstrapper, HostConfiguration configuration, params Uri[] baseUris)
{
this.bootstrapper = bootstrapper;
this.configuration = configuration ?? new HostConfiguration();
this.baseUriList = baseUris;
bootstrapper.Initialise();
this.engine = bootstrapper.GetEngine();
}
/// <summary>
/// Initializes a new instance of the <see cref="NancyHost"/> class for the specified <paramref name="baseUri"/>, using
/// the provided <paramref name="bootstrapper"/>.
/// Uses the default configuration
/// </summary>
/// <param name="baseUri">The <see cref="Uri"/> that the host will listen to.</param>
/// <param name="bootstrapper">The bootstrapper that should be used to handle the request.</param>
public NancyHost(Uri baseUri, INancyBootstrapper bootstrapper)
: this(bootstrapper, new HostConfiguration(), baseUri)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NancyHost"/> class for the specified <paramref name="baseUri"/>, using
/// the provided <paramref name="bootstrapper"/>.
/// Uses the specified configuration.
/// </summary>
/// <param name="baseUri">The <see cref="Uri"/> that the host will listen to.</param>
/// <param name="bootstrapper">The bootstrapper that should be used to handle the request.</param>
/// <param name="configuration">Configuration to use</param>
public NancyHost(Uri baseUri, INancyBootstrapper bootstrapper, HostConfiguration configuration)
: this (bootstrapper, configuration, baseUri)
{
}
/// <summary>
/// Stops the host if it is running.
/// </summary>
public void Dispose()
{
this.Stop();
this.bootstrapper.Dispose();
}
/// <summary>
/// Start listening for incoming requests with the given configuration
/// </summary>
public void Start()
{
this.StartListener();
Task.Run(() =>
{
var semaphore = new Semaphore(this.configuration.MaximumConnectionCount, this.configuration.MaximumConnectionCount);
while (!this.stop)
{
semaphore.WaitOne();
this.listener.GetContextAsync().ContinueWith(async (contextTask) =>
{
try
{
semaphore.Release();
var context = await contextTask.ConfigureAwait(false);
await this.Process(context).ConfigureAwait(false);
}
catch (Exception ex)
{
this.configuration.UnhandledExceptionCallback.Invoke(ex);
throw;
}
});
}
});
}
private void StartListener()
{
if (this.TryStartListener())
{
return;
}
if (!this.configuration.UrlReservations.CreateAutomatically)
{
throw new AutomaticUrlReservationCreationFailureException(this.GetPrefixes(), this.GetUser());
}
if (!this.TryAddUrlReservations())
{
throw new InvalidOperationException("Unable to configure namespace reservation");
}
if (!this.TryStartListener())
{
throw new InvalidOperationException("Unable to start listener");
}
}
private bool TryStartListener()
{
try
{
// if the listener fails to start, it gets disposed;
// so we need a new one, each time.
this.listener = new HttpListener();
foreach (var prefix in this.GetPrefixes())
{
this.listener.Prefixes.Add(prefix);
}
this.listener.Start();
return true;
}
catch (HttpListenerException e)
{
if (e.ErrorCode == ACCESS_DENIED)
{
return false;
}
throw;
}
}
private bool TryAddUrlReservations()
{
var user = this.GetUser();
foreach (var prefix in this.GetPrefixes())
{
if (!NetSh.AddUrlAcl(prefix, user))
{
return false;
}
}
return true;
}
private string GetUser()
{
return !string.IsNullOrWhiteSpace(this.configuration.UrlReservations.User)
? this.configuration.UrlReservations.User
: WindowsIdentity.GetCurrent().Name;
}
/// <summary>
/// Stop listening for incoming requests.
/// </summary>
public void Stop()
{
if (this.listener != null && this.listener.IsListening)
{
this.stop = true;
this.listener.Stop();
}
}
internal IEnumerable<string> GetPrefixes()
{
foreach (var baseUri in this.baseUriList)
{
var prefix = new UriBuilder(baseUri).ToString();
if (this.configuration.RewriteLocalhost && !baseUri.Host.Contains("."))
{
prefix = prefix.Replace("localhost", this.configuration.UseWeakWildcard ? "*" : "+");
}
yield return prefix;
}
}
private Request ConvertRequestToNancyRequest(HttpListenerRequest request)
{
var baseUri = this.GetBaseUri(request);
if (baseUri == null)
{
throw new InvalidOperationException(string.Format("Unable to locate base URI for request: {0}",request.Url));
}
var expectedRequestLength =
GetExpectedRequestLength(request.Headers.ToDictionary());
var nancyUrl = new Url
{
Scheme = request.Url.Scheme,
HostName = request.Url.Host,
Port = request.Url.IsDefaultPort ? null : (int?)request.Url.Port,
BasePath = baseUri.AbsolutePath.TrimEnd('/'),
Path = baseUri.MakeAppLocalPath(request.Url),
Query = request.Url.Query
};
X509Certificate2 certificate = null;
if (this.configuration.EnableClientCertificates)
{
var x509Certificate = request.GetClientCertificate();
if (x509Certificate != null)
{
certificate = x509Certificate;
}
}
// NOTE: For HTTP/2 we want fieldCount = 1,
// otherwise (HTTP/1.0 and HTTP/1.1) we want fieldCount = 2
var fieldCount = request.ProtocolVersion.Major == 2 ? 1 : 2;
var protocolVersion = string.Format("HTTP/{0}", request.ProtocolVersion.ToString(fieldCount));
return new Request(
request.HttpMethod,
nancyUrl,
RequestStream.FromStream(request.InputStream, expectedRequestLength, StaticConfiguration.DisableRequestStreamSwitching ?? false),
request.Headers.ToDictionary(),
(request.RemoteEndPoint != null) ? request.RemoteEndPoint.Address.ToString() : null,
certificate,
protocolVersion);
}
private Uri GetBaseUri(HttpListenerRequest request)
{
var result = this.baseUriList.FirstOrDefault(uri => uri.IsCaseInsensitiveBaseOf(request.Url));
if (result != null)
{
return result;
}
if (!this.configuration.AllowAuthorityFallback)
{
return null;
}
return new Uri(request.Url.GetLeftPart(UriPartial.Authority));
}
private void ConvertNancyResponseToResponse(Response nancyResponse, HttpListenerResponse response)
{
foreach (var header in nancyResponse.Headers)
{
if (!IgnoredHeaders.IsIgnored(header.Key))
{
response.AddHeader(header.Key, header.Value);
}
}
foreach (var nancyCookie in nancyResponse.Cookies)
{
response.Headers.Add(HttpResponseHeader.SetCookie, nancyCookie.ToString());
}
if (nancyResponse.ReasonPhrase != null)
{
response.StatusDescription = nancyResponse.ReasonPhrase;
}
if (nancyResponse.ContentType != null)
{
response.ContentType = nancyResponse.ContentType;
}
response.StatusCode = (int)nancyResponse.StatusCode;
if (this.configuration.AllowChunkedEncoding)
{
OutputWithDefaultTransferEncoding(nancyResponse, response);
}
else
{
OutputWithContentLength(nancyResponse, response);
}
}
private static void OutputWithDefaultTransferEncoding(Response nancyResponse, HttpListenerResponse response)
{
using (var output = response.OutputStream)
{
nancyResponse.Contents.Invoke(output);
}
}
private static void OutputWithContentLength(Response nancyResponse, HttpListenerResponse response)
{
byte[] buffer;
using (var memoryStream = new MemoryStream())
{
nancyResponse.Contents.Invoke(memoryStream);
buffer = memoryStream.ToArray();
}
string value;
var contentLength = nancyResponse.Headers.TryGetValue("Content-Length", out value) ?
Convert.ToInt64(value) :
buffer.Length;
response.SendChunked = false;
response.ContentLength64 = contentLength;
using (var output = response.OutputStream)
{
using (var writer = new BinaryWriter(output))
{
writer.Write(buffer);
writer.Flush();
}
}
}
private static long GetExpectedRequestLength(IDictionary<string, IEnumerable<string>> incomingHeaders)
{
if (incomingHeaders == null)
{
return 0;
}
IEnumerable<string> values;
if (!incomingHeaders.TryGetValue("Content-Length", out values))
{
return 0;
}
var headerValue = values.SingleOrDefault();
if (headerValue == null)
{
return 0;
}
long contentLength;
return !long.TryParse(headerValue, NumberStyles.Any, CultureInfo.InvariantCulture, out contentLength) ?
0 :
contentLength;
}
private async Task Process(HttpListenerContext ctx)
{
try
{
var nancyRequest = this.ConvertRequestToNancyRequest(ctx.Request);
using (var nancyContext = await this.engine.HandleRequest(nancyRequest).ConfigureAwait(false))
{
try
{
this.ConvertNancyResponseToResponse(nancyContext.Response, ctx.Response);
}
catch (Exception e)
{
this.configuration.UnhandledExceptionCallback.Invoke(e);
}
}
}
catch (Exception e)
{
this.configuration.UnhandledExceptionCallback.Invoke(e);
}
}
}
}