aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Net/Handlers/BaseHandler.cs
blob: 5d26c7e920acc77544f1926c2306356582525d8f (plain)
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
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Kernel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MediaBrowser.Common.Net.Handlers
{
    /// <summary>
    /// Class BaseHandler
    /// </summary>
    public abstract class BaseHandler<TKernelType> : IHttpServerHandler
        where TKernelType : IKernel
    {
        /// <summary>
        /// Initializes the specified kernel.
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        public void Initialize(IKernel kernel)
        {
            Kernel = (TKernelType)kernel;
        }

        /// <summary>
        /// Gets or sets the kernel.
        /// </summary>
        /// <value>The kernel.</value>
        protected TKernelType Kernel { get; private set; }

        /// <summary>
        /// Gets the URL suffix used to determine if this handler can process a request.
        /// </summary>
        /// <value>The URL suffix.</value>
        protected virtual string UrlSuffix
        {
            get
            {
                var name = GetType().Name;

                const string srch = "Handler";

                if (name.EndsWith(srch, StringComparison.OrdinalIgnoreCase))
                {
                    name = name.Substring(0, name.Length - srch.Length);
                }

                return "api/" + name;
            }
        }

        /// <summary>
        /// Handleses the request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public virtual bool HandlesRequest(HttpListenerRequest request)
        {
            var name = '/' + UrlSuffix.TrimStart('/');

            var url = Kernel.WebApplicationName + name;

            return request.Url.LocalPath.EndsWith(url, StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// Gets or sets the compressed stream.
        /// </summary>
        /// <value>The compressed stream.</value>
        private Stream CompressedStream { get; set; }

        /// <summary>
        /// Gets a value indicating whether [use chunked encoding].
        /// </summary>
        /// <value><c>null</c> if [use chunked encoding] contains no value, <c>true</c> if [use chunked encoding]; otherwise, <c>false</c>.</value>
        public virtual bool? UseChunkedEncoding
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// The original HttpListenerContext
        /// </summary>
        /// <value>The HTTP listener context.</value>
        protected HttpListenerContext HttpListenerContext { get; set; }

        /// <summary>
        /// The _query string
        /// </summary>
        private NameValueCollection _queryString;
        /// <summary>
        /// The original QueryString
        /// </summary>
        /// <value>The query string.</value>
        public NameValueCollection QueryString
        {
            get
            {
                // HttpListenerContext.Request.QueryString is not decoded properly
                return _queryString;
            }
        }

        /// <summary>
        /// The _requested ranges
        /// </summary>
        private List<KeyValuePair<long, long?>> _requestedRanges;
        /// <summary>
        /// Gets the requested ranges.
        /// </summary>
        /// <value>The requested ranges.</value>
        protected IEnumerable<KeyValuePair<long, long?>> RequestedRanges
        {
            get
            {
                if (_requestedRanges == null)
                {
                    _requestedRanges = new List<KeyValuePair<long, long?>>();

                    if (IsRangeRequest)
                    {
                        // Example: bytes=0-,32-63
                        var ranges = HttpListenerContext.Request.Headers["Range"].Split('=')[1].Split(',');

                        foreach (var range in ranges)
                        {
                            var vals = range.Split('-');

                            long start = 0;
                            long? end = null;

                            if (!string.IsNullOrEmpty(vals[0]))
                            {
                                start = long.Parse(vals[0]);
                            }
                            if (!string.IsNullOrEmpty(vals[1]))
                            {
                                end = long.Parse(vals[1]);
                            }

                            _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
                        }
                    }
                }

                return _requestedRanges;
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is range request.
        /// </summary>
        /// <value><c>true</c> if this instance is range request; otherwise, <c>false</c>.</value>
        protected bool IsRangeRequest
        {
            get
            {
                return HttpListenerContext.Request.Headers.AllKeys.Contains("Range");
            }
        }

        /// <summary>
        /// Gets a value indicating whether [client supports compression].
        /// </summary>
        /// <value><c>true</c> if [client supports compression]; otherwise, <c>false</c>.</value>
        protected bool ClientSupportsCompression
        {
            get
            {
                var enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;

                return enc.Equals("*", StringComparison.OrdinalIgnoreCase) ||
                    enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1 ||
                    enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1;
            }
        }

        /// <summary>
        /// Gets the compression method.
        /// </summary>
        /// <value>The compression method.</value>
        private string CompressionMethod
        {
            get
            {
                var enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;

                if (enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1 || enc.Equals("*", StringComparison.OrdinalIgnoreCase))
                {
                    return "deflate";
                }
                if (enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    return "gzip";
                }

                return null;
            }
        }

        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        /// <returns>Task.</returns>
        public virtual async Task ProcessRequest(HttpListenerContext ctx)
        {
            HttpListenerContext = ctx;

            ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");

            ctx.Response.KeepAlive = true;

            try
            {
                await ProcessRequestInternal(ctx).ConfigureAwait(false);
            }
            catch (InvalidOperationException ex)
            {
                HandleException(ctx.Response, ex, 422);

                throw;
            }
            catch (ResourceNotFoundException ex)
            {
                HandleException(ctx.Response, ex, 404);

                throw;
            }
            catch (FileNotFoundException ex)
            {
                HandleException(ctx.Response, ex, 404);

                throw;
            }
            catch (DirectoryNotFoundException ex)
            {
                HandleException(ctx.Response, ex, 404);

                throw;
            }
            catch (UnauthorizedAccessException ex)
            {
                HandleException(ctx.Response, ex, 401);

                throw;
            }
            catch (ArgumentException ex)
            {
                HandleException(ctx.Response, ex, 400);

                throw;
            }
            catch (Exception ex)
            {
                HandleException(ctx.Response, ex, 500);

                throw;
            }
            finally
            {
                DisposeResponseStream();
            }
        }

        /// <summary>
        /// Appends the error message.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="ex">The ex.</param>
        /// <param name="statusCode">The status code.</param>
        private void HandleException(HttpListenerResponse response, Exception ex, int statusCode)
        {
            response.StatusCode = statusCode;

            response.Headers.Add("Status", statusCode.ToString(new CultureInfo("en-US")));

            response.Headers.Remove("Age");
            response.Headers.Remove("Expires");
            response.Headers.Remove("Cache-Control");
            response.Headers.Remove("Etag");
            response.Headers.Remove("Last-Modified");

            response.ContentType = "text/plain";

            //Logger.ErrorException("Error processing request", ex);
            
            if (!string.IsNullOrEmpty(ex.Message))
            {
                response.AddHeader("X-Application-Error-Code", ex.Message);
            }

            var bytes = Encoding.UTF8.GetBytes(ex.Message);

            var stream = CompressedStream ?? response.OutputStream;

            // This could fail, but try to add the stack trace as the body content
            try
            {
                stream.Write(bytes, 0, bytes.Length);
            }
            catch (Exception ex1)
            {
                //Logger.ErrorException("Error dumping stack trace", ex1);
            }
        }

        /// <summary>
        /// Processes the request internal.
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        /// <returns>Task.</returns>
        private async Task ProcessRequestInternal(HttpListenerContext ctx)
        {
            var responseInfo = await GetResponseInfo().ConfigureAwait(false);

            // Let the client know if byte range requests are supported or not
            if (responseInfo.SupportsByteRangeRequests)
            {
                ctx.Response.Headers["Accept-Ranges"] = "bytes";
            }
            else if (!responseInfo.SupportsByteRangeRequests)
            {
                ctx.Response.Headers["Accept-Ranges"] = "none";
            }

            if (responseInfo.IsResponseValid && responseInfo.SupportsByteRangeRequests && IsRangeRequest)
            {
                // Set the initial status code
                // When serving a range request, we need to return status code 206 to indicate a partial response body
                responseInfo.StatusCode = 206;
            }

            ctx.Response.ContentType = responseInfo.ContentType;

            if (responseInfo.Etag.HasValue)
            {
                ctx.Response.Headers["ETag"] = responseInfo.Etag.Value.ToString("N");
            }

            var isCacheValid = true;

            // Validate If-Modified-Since
            if (ctx.Request.Headers.AllKeys.Contains("If-Modified-Since"))
            {
                DateTime ifModifiedSince;

                if (DateTime.TryParse(ctx.Request.Headers["If-Modified-Since"], out ifModifiedSince))
                {
                    isCacheValid = IsCacheValid(ifModifiedSince.ToUniversalTime(), responseInfo.CacheDuration,
                                                responseInfo.DateLastModified);
                }
            }

            // Validate If-None-Match
            if (isCacheValid &&
                (responseInfo.Etag.HasValue || !string.IsNullOrEmpty(ctx.Request.Headers["If-None-Match"])))
            {
                Guid ifNoneMatch;

                if (Guid.TryParse(ctx.Request.Headers["If-None-Match"] ?? string.Empty, out ifNoneMatch))
                {
                    if (responseInfo.Etag.HasValue && responseInfo.Etag.Value == ifNoneMatch)
                    {
                        responseInfo.StatusCode = 304;
                    }
                }
            }

            LogResponse(ctx, responseInfo);

            if (responseInfo.IsResponseValid)
            {
                await OnProcessingRequest(responseInfo).ConfigureAwait(false);
            }

            if (responseInfo.IsResponseValid)
            {
                await ProcessUncachedRequest(ctx, responseInfo).ConfigureAwait(false);
            }
            else
            {
                if (responseInfo.StatusCode == 304)
                {
                    AddAgeHeader(ctx.Response, responseInfo);
                    AddExpiresHeader(ctx.Response, responseInfo);
                }

                ctx.Response.StatusCode = responseInfo.StatusCode;
                ctx.Response.SendChunked = false;
            }
        }

        /// <summary>
        /// The _null task result
        /// </summary>
        private readonly Task<bool> _nullTaskResult = Task.FromResult(true);

        /// <summary>
        /// Called when [processing request].
        /// </summary>
        /// <param name="responseInfo">The response info.</param>
        /// <returns>Task.</returns>
        protected virtual Task OnProcessingRequest(ResponseInfo responseInfo)
        {
            return _nullTaskResult;
        }

        /// <summary>
        /// Logs the response.
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        /// <param name="responseInfo">The response info.</param>
        private void LogResponse(HttpListenerContext ctx, ResponseInfo responseInfo)
        {
            // Don't log normal 200's
            if (responseInfo.StatusCode == 200)
            {
                return;
            }

            var log = new StringBuilder();

            log.AppendLine(string.Format("Url: {0}", ctx.Request.Url));

            log.AppendLine("Headers: " + string.Join(",", ctx.Response.Headers.AllKeys.Select(k => k + "=" + ctx.Response.Headers[k])));

            var msg = "Http Response Sent (" + responseInfo.StatusCode + ") to " + ctx.Request.RemoteEndPoint;

            if (Kernel.Configuration.EnableHttpLevelLogging)
            {
                //Logger.LogMultiline(msg, LogSeverity.Debug, log);
            }
        }

        /// <summary>
        /// Processes the uncached request.
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        /// <param name="responseInfo">The response info.</param>
        /// <returns>Task.</returns>
        private async Task ProcessUncachedRequest(HttpListenerContext ctx, ResponseInfo responseInfo)
        {
            var totalContentLength = GetTotalContentLength(responseInfo);

            // By default, use chunked encoding if we don't know the content length
            var useChunkedEncoding = UseChunkedEncoding == null ? (totalContentLength == null) : UseChunkedEncoding.Value;

            // Don't force this to true. HttpListener will default it to true if supported by the client.
            if (!useChunkedEncoding)
            {
                ctx.Response.SendChunked = false;
            }

            // Set the content length, if we know it
            if (totalContentLength.HasValue)
            {
                ctx.Response.ContentLength64 = totalContentLength.Value;
            }

            var compressResponse = responseInfo.CompressResponse && ClientSupportsCompression;

            // Add the compression header
            if (compressResponse)
            {
                ctx.Response.AddHeader("Content-Encoding", CompressionMethod);
                ctx.Response.AddHeader("Vary", "Accept-Encoding");
            }

            // Don't specify both last modified and Etag, unless caching unconditionally. They are redundant
            // https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
            if (responseInfo.DateLastModified.HasValue && (!responseInfo.Etag.HasValue || responseInfo.CacheDuration.Ticks > 0))
            {
                ctx.Response.Headers[HttpResponseHeader.LastModified] = responseInfo.DateLastModified.Value.ToString("r");
                AddAgeHeader(ctx.Response, responseInfo);
            }

            // Add caching headers
            ConfigureCaching(ctx.Response, responseInfo);

            // Set the status code
            ctx.Response.StatusCode = responseInfo.StatusCode;

            if (responseInfo.IsResponseValid)
            {
                // Finally, write the response data
                var outputStream = ctx.Response.OutputStream;

                if (compressResponse)
                {
                    if (CompressionMethod.Equals("deflate", StringComparison.OrdinalIgnoreCase))
                    {
                        CompressedStream = new DeflateStream(outputStream, CompressionLevel.Fastest, true);
                    }
                    else
                    {
                        CompressedStream = new GZipStream(outputStream, CompressionLevel.Fastest, true);
                    }

                    outputStream = CompressedStream;
                }

                await WriteResponseToOutputStream(outputStream, responseInfo, totalContentLength).ConfigureAwait(false);
            }
            else
            {
                ctx.Response.SendChunked = false;
            }
        }

        /// <summary>
        /// Configures the caching.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="responseInfo">The response info.</param>
        private void ConfigureCaching(HttpListenerResponse response, ResponseInfo responseInfo)
        {
            if (responseInfo.CacheDuration.Ticks > 0)
            {
                response.Headers[HttpResponseHeader.CacheControl] = "public, max-age=" + Convert.ToInt32(responseInfo.CacheDuration.TotalSeconds);
            }
            else if (responseInfo.Etag.HasValue)
            {
                response.Headers[HttpResponseHeader.CacheControl] = "public";
            }
            else
            {
                response.Headers[HttpResponseHeader.CacheControl] = "no-cache, no-store, must-revalidate";
                response.Headers[HttpResponseHeader.Pragma] = "no-cache, no-store, must-revalidate";
            }

            AddExpiresHeader(response, responseInfo);
        }

        /// <summary>
        /// Adds the expires header.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="responseInfo">The response info.</param>
        private void AddExpiresHeader(HttpListenerResponse response, ResponseInfo responseInfo)
        {
            if (responseInfo.CacheDuration.Ticks > 0)
            {
                response.Headers[HttpResponseHeader.Expires] = DateTime.UtcNow.Add(responseInfo.CacheDuration).ToString("r");
            }
            else if (!responseInfo.Etag.HasValue)
            {
                response.Headers[HttpResponseHeader.Expires] = "-1";
            }
        }

        /// <summary>
        /// Adds the age header.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="responseInfo">The response info.</param>
        private void AddAgeHeader(HttpListenerResponse response, ResponseInfo responseInfo)
        {
            if (responseInfo.DateLastModified.HasValue)
            {
                response.Headers[HttpResponseHeader.Age] = Convert.ToInt32((DateTime.UtcNow - responseInfo.DateLastModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
            }
        }

        /// <summary>
        /// Writes the response to output stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="responseInfo">The response info.</param>
        /// <param name="contentLength">Length of the content.</param>
        /// <returns>Task.</returns>
        protected abstract Task WriteResponseToOutputStream(Stream stream, ResponseInfo responseInfo, long? contentLength);

        /// <summary>
        /// Disposes the response stream.
        /// </summary>
        protected virtual void DisposeResponseStream()
        {
            if (CompressedStream != null)
            {
                try
                {
                    CompressedStream.Dispose();
                }
                catch (Exception ex)
                {
                    //Logger.ErrorException("Error disposing compressed stream", ex);
                }
            }

            try
            {
                //HttpListenerContext.Response.OutputStream.Dispose();
                HttpListenerContext.Response.Close();
            }
            catch (Exception ex)
            {
                //Logger.ErrorException("Error disposing response", ex);
            }
        }

        /// <summary>
        /// Determines whether [is cache valid] [the specified if modified since].
        /// </summary>
        /// <param name="ifModifiedSince">If modified since.</param>
        /// <param name="cacheDuration">Duration of the cache.</param>
        /// <param name="dateModified">The date modified.</param>
        /// <returns><c>true</c> if [is cache valid] [the specified if modified since]; otherwise, <c>false</c>.</returns>
        private bool IsCacheValid(DateTime ifModifiedSince, TimeSpan cacheDuration, DateTime? dateModified)
        {
            if (dateModified.HasValue)
            {
                DateTime lastModified = NormalizeDateForComparison(dateModified.Value);
                ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);

                return lastModified <= ifModifiedSince;
            }

            DateTime cacheExpirationDate = ifModifiedSince.Add(cacheDuration);

            if (DateTime.UtcNow < cacheExpirationDate)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
        /// </summary>
        /// <param name="date">The date.</param>
        /// <returns>DateTime.</returns>
        private DateTime NormalizeDateForComparison(DateTime date)
        {
            return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
        }

        /// <summary>
        /// Gets the total length of the content.
        /// </summary>
        /// <param name="responseInfo">The response info.</param>
        /// <returns>System.Nullable{System.Int64}.</returns>
        protected virtual long? GetTotalContentLength(ResponseInfo responseInfo)
        {
            return null;
        }

        /// <summary>
        /// Gets the response info.
        /// </summary>
        /// <returns>Task{ResponseInfo}.</returns>
        protected abstract Task<ResponseInfo> GetResponseInfo();

        /// <summary>
        /// Gets a bool query string param.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        protected bool GetBoolQueryStringParam(string name)
        {
            var val = QueryString[name] ?? string.Empty;

            return val.Equals("1", StringComparison.OrdinalIgnoreCase) || val.Equals("true", StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// The _form values
        /// </summary>
        private Hashtable _formValues;

        /// <summary>
        /// Gets a value from form POST data
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns>Task{System.String}.</returns>
        protected async Task<string> GetFormValue(string name)
        {
            if (_formValues == null)
            {
                _formValues = await GetFormValues(HttpListenerContext.Request).ConfigureAwait(false);
            }

            if (_formValues.ContainsKey(name))
            {
                return _formValues[name].ToString();
            }

            return null;
        }

        /// <summary>
        /// Extracts form POST data from a request
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Task{Hashtable}.</returns>
        private async Task<Hashtable> GetFormValues(HttpListenerRequest request)
        {
            var formVars = new Hashtable();

            if (request.HasEntityBody)
            {
                if (request.ContentType.IndexOf("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    using (var requestBody = request.InputStream)
                    {
                        using (var reader = new StreamReader(requestBody, request.ContentEncoding))
                        {
                            var s = await reader.ReadToEndAsync().ConfigureAwait(false);

                            var pairs = s.Split('&');

                            foreach (var pair in pairs)
                            {
                                var index = pair.IndexOf('=');

                                if (index != -1)
                                {
                                    var name = pair.Substring(0, index);
                                    var value = pair.Substring(index + 1);
                                    formVars.Add(name, value);
                                }
                            }
                        }
                    }
                }
            }

            return formVars;
        }
    }

    /// <summary>
    /// Class ResponseInfo
    /// </summary>
    public class ResponseInfo
    {
        /// <summary>
        /// Gets or sets the type of the content.
        /// </summary>
        /// <value>The type of the content.</value>
        public string ContentType { get; set; }
        /// <summary>
        /// Gets or sets the etag.
        /// </summary>
        /// <value>The etag.</value>
        public Guid? Etag { get; set; }
        /// <summary>
        /// Gets or sets the date last modified.
        /// </summary>
        /// <value>The date last modified.</value>
        public DateTime? DateLastModified { get; set; }
        /// <summary>
        /// Gets or sets the duration of the cache.
        /// </summary>
        /// <value>The duration of the cache.</value>
        public TimeSpan CacheDuration { get; set; }
        /// <summary>
        /// Gets or sets a value indicating whether [compress response].
        /// </summary>
        /// <value><c>true</c> if [compress response]; otherwise, <c>false</c>.</value>
        public bool CompressResponse { get; set; }
        /// <summary>
        /// Gets or sets the status code.
        /// </summary>
        /// <value>The status code.</value>
        public int StatusCode { get; set; }
        /// <summary>
        /// Gets or sets a value indicating whether [supports byte range requests].
        /// </summary>
        /// <value><c>true</c> if [supports byte range requests]; otherwise, <c>false</c>.</value>
        public bool SupportsByteRangeRequests { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ResponseInfo" /> class.
        /// </summary>
        public ResponseInfo()
        {
            CacheDuration = TimeSpan.FromTicks(0);

            CompressResponse = true;

            StatusCode = 200;
        }

        /// <summary>
        /// Gets a value indicating whether this instance is response valid.
        /// </summary>
        /// <value><c>true</c> if this instance is response valid; otherwise, <c>false</c>.</value>
        public bool IsResponseValid
        {
            get
            {
                return StatusCode >= 200 && StatusCode < 300;
            }
        }
    }
}