-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathHttpListenerRequest.cs
693 lines (608 loc) · 16.4 KB
/
HttpListenerRequest.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
//
// System.Net.HttpListenerRequest
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
// Marek Safar ([email protected])
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2011-2012 Xamarin, Inc. (http://xamarin.com)
// Copyright (c) 2018 Nivloc Enterprises Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if SECURITY_DEP
using System;
#if SSHARP
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using SSMono.Security.Cryptography.X509Certificates;
using IAsyncResult = Crestron.SimplSharp.CrestronIO.IAsyncResult;
using AsyncCallback = Crestron.SimplSharp.CrestronIO.AsyncCallback;
using Crestron.SimplSharp.Net;
#else
using System.IO;
using System.Security.Cryptography.X509Certificates;
#if MONOTOUCH || MONODROID
using Mono.Security.Protocol.Tls;
#else
extern alias MonoSecurity;
using MonoSecurity::Mono.Security.Protocol.Tls;
#endif
#endif
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Text;
#if NET_4_0 && !NETCF
using System.Security.Authentication.ExtendedProtection;
#endif
#if NET_4_5
using System.Threading.Tasks;
#endif
#if SSHARP
namespace SSMono.Net
#else
namespace System.Net
#endif
{
public sealed class HttpListenerRequest
{
#if NET_4_0 && !NETCF
class Context : TransportContext
{
public override ChannelBinding GetChannelBinding (ChannelBindingKind kind)
{
throw new NotImplementedException ();
}
}
#endif
private string[] accept_types;
private Encoding content_encoding;
private long content_length;
private bool cl_set;
private CookieCollection cookies;
private WebHeaderCollection headers;
private string method;
private Stream input_stream;
private Version version;
private NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
private string raw_url;
private Uri url;
private Uri referrer;
private string[] user_languages;
private HttpListenerContext context;
private bool is_chunked;
private bool ka_set;
private bool keep_alive;
private delegate X509Certificate2 GCCDelegate ();
private GCCDelegate gcc_delegate;
private static byte[] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
internal HttpListenerRequest (HttpListenerContext context)
{
this.context = context;
headers = new WebHeaderCollection ();
version = HttpVersion.Version10;
}
private static char[] separators = new char[] {' '};
internal void SetRequestLine (string req)
{
string[] parts = req.Split (separators, 3);
if (parts.Length != 3)
{
context.ErrorMessage = "Invalid request line (parts).";
return;
}
method = parts[0];
foreach (char c in method)
{
int ic = (int)c;
if ((ic >= 'A' && ic <= 'Z')
|| (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' && c != '<' && c != '>' && c != '@' && c != ',' && c != ';' && c != ':' && c != '\\' && c != '"'
&& c != '/' && c != '[' && c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
continue;
context.ErrorMessage = "(Invalid verb)";
return;
}
raw_url = parts[1];
if (parts[2].Length != 8 || !parts[2].StartsWith ("HTTP/"))
{
context.ErrorMessage = "Invalid request line (version).";
return;
}
try
{
version = new Version (parts[2].Substring (5));
if (version.Major < 1)
throw new Exception ();
}
catch
{
context.ErrorMessage = "Invalid request line (version).";
return;
}
}
private void CreateQueryString (string query)
{
if (query == null || query.Length == 0)
{
query_string = new NameValueCollection (1);
return;
}
query_string = new NameValueCollection ();
if (query[0] == '?')
query = query.Substring (1);
string[] components = query.Split ('&');
foreach (string kv in components)
{
int pos = kv.IndexOf ('=');
if (pos == -1)
query_string.Add (null, HttpUtility.UrlDecode (kv));
else
{
string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
query_string.Add (key, val);
}
}
}
#if SSHARP
internal static bool MaybeUri (string s)
{
int p = s.IndexOf (':');
if (p == -1)
return false;
if (p >= 10)
return false;
return IsPredefinedScheme (s.Substring (0, p));
}
//
// Using a simple block of if's is twice as slow as the compiler generated
// switch statement. But using this tuned code is faster than the
// compiler generated code, with a million loops on x86-64:
//
// With "http": .10 vs .51 (first check)
// with "https": .16 vs .51 (second check)
// with "foo": .22 vs .31 (never found)
// with "mailto": .12 vs .51 (last check)
//
//
private static bool IsPredefinedScheme (string scheme)
{
if (scheme == null || scheme.Length < 3)
return false;
char c = scheme[0];
if (c == 'h')
return (scheme == "http" || scheme == "https");
if (c == 'f')
return (scheme == "file" || scheme == "ftp");
if (c == 'n')
{
c = scheme[1];
if (c == 'e')
return (scheme == "news" || scheme == "net.pipe" || scheme == "net.tcp");
if (scheme == "nntp")
return true;
return false;
}
if ((c == 'g' && scheme == "gopher") || (c == 'm' && scheme == "mailto"))
return true;
return false;
}
#endif
internal void FinishInitialization ()
{
string host = UserHostName;
if (version > HttpVersion.Version10 && (host == null || host.Length == 0))
{
context.ErrorMessage = "Invalid host name";
return;
}
string path;
Uri raw_uri = null;
#if SSHARP
if (MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
#else
if (Uri.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
#endif
path = raw_uri.PathAndQuery;
else
path = raw_url;
if ((host == null || host.Length == 0))
host = UserHostAddress;
if (raw_uri != null)
host = raw_uri.Host;
int colon = host.IndexOf (':');
if (colon >= 0)
host = host.Substring (0, colon);
string base_uri = String.Format ("{0}://{1}:{2}", (IsSecureConnection) ? "https" : "http", host, LocalEndPoint.Port);
if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url))
{
context.ErrorMessage = "Invalid url: " + base_uri + path;
return;
}
CreateQueryString (url.Query);
if (version >= HttpVersion.Version11)
{
string t_encoding = Headers["Transfer-Encoding"];
is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
// 'identity' is not valid!
if (t_encoding != null && !is_chunked)
{
context.Connection.SendError (null, 501);
return;
}
}
if (!is_chunked && !cl_set)
{
if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 || String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0)
{
context.Connection.SendError (null, 411);
return;
}
}
if (String.Compare (Headers["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0)
{
ResponseStream output = context.Connection.GetResponseStream ();
output.InternalWrite (_100continue, 0, _100continue.Length);
}
}
internal static string Unquote (String str)
{
int start = str.IndexOf ('\"');
int end = str.LastIndexOf ('\"');
if (start >= 0 && end >= 0)
str = str.Substring (start + 1, end - 1);
return str.Trim ();
}
internal void AddHeader (string header)
{
int colon = header.IndexOf (':');
if (colon == -1 || colon == 0)
{
context.ErrorMessage = "Bad Request";
context.ErrorStatus = 400;
return;
}
string name = header.Substring (0, colon).Trim ();
string val = header.Substring (colon + 1).Trim ();
string lower = name.ToLower (CultureInfo.InvariantCulture);
headers.SetInternal (name, val);
switch (lower)
{
case "accept-language":
user_languages = val.Split (','); // yes, only split with a ','
break;
case "accept":
accept_types = val.Split (','); // yes, only split with a ','
break;
case "content-length":
try
{
//TODO: max. content_length?
content_length = Int64.Parse (val.Trim ());
if (content_length < 0)
context.ErrorMessage = "Invalid Content-Length.";
cl_set = true;
}
catch
{
context.ErrorMessage = "Invalid Content-Length.";
}
break;
case "referer":
try
{
referrer = new Uri (val);
}
catch
{
referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
}
break;
case "cookie":
if (cookies == null)
cookies = new CookieCollection ();
string[] cookieStrings = val.Split (new char[] {',', ';'});
Cookie current = null;
int version = 0;
foreach (string cookieString in cookieStrings)
{
string str = cookieString.Trim ();
if (str.Length == 0)
continue;
if (str.StartsWith ("$Version"))
version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
else if (str.StartsWith ("$Path"))
{
if (current != null)
current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
}
else if (str.StartsWith ("$Domain"))
{
if (current != null)
current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
}
else if (str.StartsWith ("$Port"))
{
if (current != null)
current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
}
else
{
if (current != null)
cookies.Add (current);
current = new Cookie ();
int idx = str.IndexOf ('=');
if (idx > 0)
{
current.Name = str.Substring (0, idx).Trim ();
current.Value = str.Substring (idx + 1).Trim ();
}
else
{
current.Name = str.Trim ();
current.Value = String.Empty;
}
current.Version = version;
}
}
if (current != null)
cookies.Add (current);
break;
}
}
// returns true is the stream could be reused.
internal bool FlushInput ()
{
if (!HasEntityBody)
return true;
int length = 2048;
if (content_length > 0)
length = (int)Math.Min (content_length, (long)length);
byte[] bytes = new byte[length];
while (true)
{
// TODO: test if MS has a timeout when doing this
try
{
IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (1000))
return false;
if (InputStream.EndRead (ares) <= 0)
return true;
}
catch
{
return false;
}
}
}
public string[] AcceptTypes
{
get { return accept_types; }
}
public int ClientCertificateError
{
get
{
HttpConnection cnc = context.Connection;
if (cnc.ClientCertificate == null)
throw new InvalidOperationException ("No client certificate");
int[] errors = cnc.ClientCertificateErrors;
if (errors != null && errors.Length > 0)
return errors[0];
return 0;
}
}
public Encoding ContentEncoding
{
get
{
if (content_encoding == null)
content_encoding = Encoding.Default;
return content_encoding;
}
}
public long ContentLength64
{
get { return content_length; }
}
public string ContentType
{
get { return headers["content-type"]; }
}
public CookieCollection Cookies
{
get
{
// TODO: check if the collection is read-only
if (cookies == null)
cookies = new CookieCollection ();
return cookies;
}
}
public bool HasEntityBody
{
get { return (content_length > 0 || is_chunked); }
}
public NameValueCollection Headers
{
get { return headers; }
}
public string HttpMethod
{
get { return method; }
}
public Stream InputStream
{
get
{
if (input_stream == null)
{
if (is_chunked || content_length > 0)
input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
else
input_stream = Stream.Null;
}
return input_stream;
}
}
[MonoTODO ("Always returns false")]
public bool IsAuthenticated
{
get { return false; }
}
public bool IsLocal
{
get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
}
public bool IsSecureConnection
{
get { return context.Connection.IsSecure; }
}
public bool KeepAlive
{
get
{
if (ka_set)
return keep_alive;
ka_set = true;
// 1. Connection header
// 2. Protocol (1.1 == keep-alive by default)
// 3. Keep-Alive header
string cnc = headers["Connection"];
if (!String.IsNullOrEmpty (cnc))
keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
else if (version == HttpVersion.Version11)
keep_alive = true;
else
{
cnc = headers["keep-alive"];
if (!String.IsNullOrEmpty (cnc))
keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
}
return keep_alive;
}
}
public IPEndPoint LocalEndPoint
{
get { return context.Connection.LocalEndPoint; }
}
public Version ProtocolVersion
{
get { return version; }
}
public NameValueCollection QueryString
{
get { return query_string; }
}
public string RawUrl
{
get { return raw_url; }
}
public IPEndPoint RemoteEndPoint
{
get { return context.Connection.RemoteEndPoint; }
}
[MonoTODO ("Always returns Guid.Empty")]
public Guid RequestTraceIdentifier
{
get { return Guid.Empty; }
}
public Uri Url
{
get { return url; }
}
public Uri UrlReferrer
{
get { return referrer; }
}
public string UserAgent
{
get { return headers["user-agent"]; }
}
public string UserHostAddress
{
get { return LocalEndPoint.ToString (); }
}
public string UserHostName
{
get { return headers["host"]; }
}
public string[] UserLanguages
{
get { return user_languages; }
}
public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
{
if (gcc_delegate == null)
gcc_delegate = new GCCDelegate (GetClientCertificate);
#if SSHARP
return gcc_delegate.BeginInvokeEx (requestCallback, state);
#else
return gcc_delegate.BeginInvoke (requestCallback, state);
#endif
}
public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException ("asyncResult");
if (gcc_delegate == null)
throw new InvalidOperationException ();
#if SSHARP
return gcc_delegate.EndInvokeEx<X509Certificate2> (asyncResult);
#else
return gcc_delegate.EndInvoke (asyncResult);
#endif
}
public X509Certificate2 GetClientCertificate ()
{
return context.Connection.ClientCertificate;
}
#if NET_4_0
[MonoTODO]
public string ServiceName
{
get { return null; }
}
#if !NETCF
public TransportContext TransportContext {
get {
return new Context ();
}
}
#endif
#endif
#if NET_4_5
[MonoTODO]
public bool IsWebSocketRequest {
get {
return false;
}
}
public Task<X509Certificate2> GetClientCertificateAsync ()
{
return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);
}
#endif
}
}
#endif