[System] HttpListenerRequest: ignore bad cookies and keep request alive (#5657)
[mono.git] / mcs / class / System / System.Net / HttpListenerRequest.cs
1 //
2 // System.Net.HttpListenerRequest
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
6 //      Marek Safar (marek.safar@gmail.com)
7 //
8 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
9 // Copyright (c) 2011-2012 Xamarin, Inc. (http://xamarin.com)
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System.Collections;
32 using System.Collections.Specialized;
33 using System.Globalization;
34 using System.IO;
35 using System.Security.Cryptography.X509Certificates;
36 using System.Text;
37 using System.Security.Authentication.ExtendedProtection;
38 using System.Threading.Tasks;
39 using System.Net;
40
41 namespace System.Net {
42         public sealed class HttpListenerRequest
43         {
44                 class Context : TransportContext
45                 {
46                         public override ChannelBinding GetChannelBinding (ChannelBindingKind kind)
47                         {
48                                 throw new NotImplementedException ();
49                         }
50                 }
51
52                 string [] accept_types;
53                 Encoding content_encoding;
54                 long content_length;
55                 bool cl_set;
56                 CookieCollection cookies;
57                 WebHeaderCollection headers;
58                 string method;
59                 Stream input_stream;
60                 Version version;
61                 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
62                 string raw_url;
63                 Uri url;
64                 Uri referrer;
65                 string [] user_languages;
66                 HttpListenerContext context;
67                 bool is_chunked;
68                 bool ka_set;
69                 bool keep_alive;
70                 delegate X509Certificate2 GCCDelegate ();
71                 GCCDelegate gcc_delegate;
72
73                 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
74
75                 internal HttpListenerRequest (HttpListenerContext context)
76                 {
77                         this.context = context;
78                         headers = new WebHeaderCollection ();
79                         version = HttpVersion.Version10;
80                 }
81
82                 static char [] separators = new char [] { ' ' };
83
84                 internal void SetRequestLine (string req)
85                 {
86                         string [] parts = req.Split (separators, 3);
87                         if (parts.Length != 3) {
88                                 context.ErrorMessage = "Invalid request line (parts).";
89                                 return;
90                         }
91
92                         method = parts [0];
93                         foreach (char c in method){
94                                 int ic = (int) c;
95
96                                 if ((ic >= 'A' && ic <= 'Z') ||
97                                     (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
98                                      c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
99                                      c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
100                                      c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
101                                         continue;
102
103                                 context.ErrorMessage = "(Invalid verb)";
104                                 return;
105                         }
106
107                         raw_url = parts [1];
108                         if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
109                                 context.ErrorMessage = "Invalid request line (version).";
110                                 return;
111                         }
112
113                         try {
114                                 version = new Version (parts [2].Substring (5));
115                                 if (version.Major < 1)
116                                         throw new Exception ();
117                         } catch {
118                                 context.ErrorMessage = "Invalid request line (version).";
119                                 return;
120                         }
121                 }
122
123                 void CreateQueryString (string query)
124                 {
125                         if (query == null || query.Length == 0) {
126                                 query_string = new NameValueCollection (1);
127                                 return;
128                         }
129
130                         query_string = new NameValueCollection ();
131                         if (query [0] == '?')
132                                 query = query.Substring (1);
133                         string [] components = query.Split ('&');
134                         foreach (string kv in components) {
135                                 int pos = kv.IndexOf ('=');
136                                 if (pos == -1) {
137                                         query_string.Add (null, WebUtility.UrlDecode (kv));
138                                 } else {
139                                         string key = WebUtility.UrlDecode (kv.Substring (0, pos));
140                                         string val = WebUtility.UrlDecode (kv.Substring (pos + 1));
141                                         
142                                         query_string.Add (key, val);
143                                 }
144                         }
145                 }
146
147                 static bool MaybeUri (string s)
148                 {
149                         int p = s.IndexOf (':');
150                         if (p == -1)
151                                 return false;
152
153                         if (p >= 10)
154                                 return false;
155
156                         return IsPredefinedScheme (s.Substring (0, p));
157                 }
158
159                 //
160                 // Using a simple block of if's is twice as slow as the compiler generated
161                 // switch statement.   But using this tuned code is faster than the
162                 // compiler generated code, with a million loops on x86-64:
163                 //
164                 // With "http": .10 vs .51 (first check)
165                 // with "https": .16 vs .51 (second check)
166                 // with "foo": .22 vs .31 (never found)
167                 // with "mailto": .12 vs .51  (last check)
168                 //
169                 //
170                 static bool IsPredefinedScheme (string scheme)
171                 {
172                         if (scheme == null || scheme.Length < 3)
173                                 return false;
174                         
175                         char c = scheme [0];
176                         if (c == 'h')
177                                 return (scheme == "http" || scheme == "https");
178                         if (c == 'f')
179                                 return (scheme == "file" || scheme == "ftp");
180                                 
181                         if (c == 'n'){
182                                 c = scheme [1];
183                                 if (c == 'e')
184                                         return (scheme == "news" || scheme == "net.pipe" || scheme == "net.tcp");
185                                 if (scheme == "nntp")
186                                         return true;
187                                 return false;
188                         }
189                         if ((c == 'g' && scheme == "gopher") || (c == 'm' && scheme == "mailto"))
190                                 return true;
191
192                         return false;
193                 }
194
195                 internal void FinishInitialization ()
196                 {
197                         string host = UserHostName;
198                         if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
199                                 context.ErrorMessage = "Invalid host name";
200                                 return;
201                         }
202
203                         string path;
204                         Uri raw_uri = null;
205                         if (MaybeUri (raw_url.ToLowerInvariant ()) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
206                                 path = raw_uri.PathAndQuery;
207                         else
208                                 path = raw_url;
209
210                         if ((host == null || host.Length == 0))
211                                 host = UserHostAddress;
212
213                         if (raw_uri != null)
214                                 host = raw_uri.Host;
215         
216                         int colon = host.IndexOf (':');
217                         if (colon >= 0)
218                                 host = host.Substring (0, colon);
219
220                         string base_uri = String.Format ("{0}://{1}:{2}",
221                                                                 (IsSecureConnection) ? "https" : "http",
222                                                                 host, LocalEndPoint.Port);
223
224                         if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
225                                 context.ErrorMessage = WebUtility.HtmlEncode ("Invalid url: " + base_uri + path);
226                                 return;
227                         }
228
229                         CreateQueryString (url.Query);
230
231                         // Use reference source HttpListenerRequestUriBuilder to process url.
232                         // Fixes #29927
233                         url = HttpListenerRequestUriBuilder.GetRequestUri (raw_url, url.Scheme,
234                                                                 url.Authority, url.LocalPath, url.Query);
235
236                         if (version >= HttpVersion.Version11) {
237                                 string t_encoding = Headers ["Transfer-Encoding"];
238                                 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
239                                 // 'identity' is not valid!
240                                 if (t_encoding != null && !is_chunked) {
241                                         context.Connection.SendError (null, 501);
242                                         return;
243                                 }
244                         }
245
246                         if (!is_chunked && !cl_set) {
247                                 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
248                                     String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
249                                         context.Connection.SendError (null, 411);
250                                         return;
251                                 }
252                         }
253
254                         if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
255                                 ResponseStream output = context.Connection.GetResponseStream ();
256                                 output.InternalWrite (_100continue, 0, _100continue.Length);
257                         }
258                 }
259
260                 internal static string Unquote (String str) {
261                         int start = str.IndexOf ('\"');
262                         int end = str.LastIndexOf ('\"');
263                         if (start >= 0 && end >=0)
264                                 str = str.Substring (start + 1, end - 1);
265                         return str.Trim ();
266                 }
267
268                 internal void AddHeader (string header)
269                 {
270                         int colon = header.IndexOf (':');
271                         if (colon == -1 || colon == 0) {
272                                 context.ErrorMessage = "Bad Request";
273                                 context.ErrorStatus = 400;
274                                 return;
275                         }
276
277                         string name = header.Substring (0, colon).Trim ();
278                         string val = header.Substring (colon + 1).Trim ();
279                         string lower = name.ToLower (CultureInfo.InvariantCulture);
280                         headers.SetInternal (name, val);
281                         switch (lower) {
282                                 case "accept-language":
283                                         user_languages = val.Split (','); // yes, only split with a ','
284                                         break;
285                                 case "accept":
286                                         accept_types = val.Split (','); // yes, only split with a ','
287                                         break;
288                                 case "content-length":
289                                         try {
290                                                 //TODO: max. content_length?
291                                                 content_length = Int64.Parse (val.Trim ());
292                                                 if (content_length < 0)
293                                                         context.ErrorMessage = "Invalid Content-Length.";
294                                                 cl_set = true;
295                                         } catch {
296                                                 context.ErrorMessage = "Invalid Content-Length.";
297                                         }
298
299                                         break;
300                                 case "referer":
301                                         try {
302                                                 referrer = new Uri (val);
303                                         } catch {
304                                                 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
305                                         }
306                                         break;
307                                 case "cookie":
308                                         if (cookies == null)
309                                                 cookies = new CookieCollection();
310
311                                         string[] cookieStrings = val.Split(new char[] {',', ';'});
312                                         Cookie current = null;
313                                         int version = 0;
314                                         foreach (string cookieString in cookieStrings) {
315                                                 string str = cookieString.Trim ();
316                                                 if (str.Length == 0)
317                                                         continue;
318                                                 if (str.StartsWith ("$Version")) {
319                                                         version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
320                                                 } else if (str.StartsWith ("$Path")) {
321                                                         if (current != null)
322                                                                 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
323                                                 } else if (str.StartsWith ("$Domain")) {
324                                                         if (current != null)
325                                                                 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
326                                                 } else if (str.StartsWith ("$Port")) {
327                                                         if (current != null)
328                                                                 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
329                                                 } else {
330                                                         if (current != null) {
331                                                                 cookies.Add (current);
332                                                         }
333                                                         try {
334                                                                 current = new Cookie ();
335                                                                 int idx = str.IndexOf ('=');
336                                                                 if (idx > 0) {
337                                                                         current.Name = str.Substring (0, idx).Trim ();
338                                                                         current.Value =  str.Substring (idx + 1).Trim ();
339                                                                 } else {
340                                                                         current.Name = str.Trim ();
341                                                                         current.Value = String.Empty;
342                                                                 }
343                                                                 current.Version = version;
344                                                         } catch (CookieException) {
345                                                                 current = null;
346                                                         }
347                                                 }
348                                         }
349                                         if (current != null) {
350                                                 cookies.Add (current);
351                                         }
352                                         break;
353                         }
354                 }
355
356                 // returns true is the stream could be reused.
357                 internal bool FlushInput ()
358                 {
359                         if (!HasEntityBody)
360                                 return true;
361
362                         int length = 2048;
363                         if (content_length > 0)
364                                 length = (int) Math.Min (content_length, (long) length);
365
366                         byte [] bytes = new byte [length];
367                         while (true) {
368                                 // TODO: test if MS has a timeout when doing this
369                                 try {
370                                         IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
371                                         if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (1000))
372                                                 return false;
373                                         if (InputStream.EndRead (ares) <= 0)
374                                                 return true;
375                                 } catch (ObjectDisposedException) {
376                                         input_stream = null;
377                                         return true;
378                                 } catch {
379                                         return false;
380                                 }
381                         }
382                 }
383
384                 public string [] AcceptTypes {
385                         get { return accept_types; }
386                 }
387
388                 public int ClientCertificateError {
389                         get {
390                                 HttpConnection cnc = context.Connection;
391                                 if (cnc.ClientCertificate == null)
392                                         throw new InvalidOperationException ("No client certificate");
393                                 int [] errors = cnc.ClientCertificateErrors;
394                                 if (errors != null && errors.Length > 0)
395                                         return errors [0];
396                                 return 0;
397                         }
398                 }
399
400                 public Encoding ContentEncoding {
401                         get {
402                                 if (content_encoding == null)
403                                         content_encoding = Encoding.Default;
404                                 return content_encoding;
405                         }
406                 }
407
408                 public long ContentLength64 {
409                         get { return is_chunked ? -1 : content_length; }
410                 }
411
412                 public string ContentType {
413                         get { return headers ["content-type"]; }
414                 }
415
416                 public CookieCollection Cookies {
417                         get {
418                                 // TODO: check if the collection is read-only
419                                 if (cookies == null)
420                                         cookies = new CookieCollection ();
421                                 return cookies;
422                         }
423                 }
424
425                 public bool HasEntityBody {
426                         get { return (content_length > 0 || is_chunked); }
427                 }
428
429                 public NameValueCollection Headers {
430                         get { return headers; }
431                 }
432
433                 public string HttpMethod {
434                         get { return method; }
435                 }
436
437                 public Stream InputStream {
438                         get {
439                                 if (input_stream == null) {
440                                         if (is_chunked || content_length > 0)
441                                                 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
442                                         else
443                                                 input_stream = Stream.Null;
444                                 }
445
446                                 return input_stream;
447                         }
448                 }
449
450                 [MonoTODO ("Always returns false")]
451                 public bool IsAuthenticated {
452                         get { return false; }
453                 }
454
455                 public bool IsLocal {
456                         get { return LocalEndPoint.Address.Equals (RemoteEndPoint.Address); }
457                 }
458
459                 public bool IsSecureConnection {
460                         get { return context.Connection.IsSecure; } 
461                 }
462
463                 public bool KeepAlive {
464                         get {
465                                 if (ka_set)
466                                         return keep_alive;
467
468                                 ka_set = true;
469                                 // 1. Connection header
470                                 // 2. Protocol (1.1 == keep-alive by default)
471                                 // 3. Keep-Alive header
472                                 string cnc = headers ["Connection"];
473                                 if (!String.IsNullOrEmpty (cnc)) {
474                                         keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
475                                 } else if (version == HttpVersion.Version11) {
476                                         keep_alive = true;
477                                 } else {
478                                         cnc = headers ["keep-alive"];
479                                         if (!String.IsNullOrEmpty (cnc))
480                                                 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
481                                 }
482                                 return keep_alive;
483                         }
484                 }
485
486                 public IPEndPoint LocalEndPoint {
487                         get { return context.Connection.LocalEndPoint; }
488                 }
489
490                 public Version ProtocolVersion {
491                         get { return version; }
492                 }
493
494                 public NameValueCollection QueryString {
495                         get { return query_string; }
496                 }
497
498                 public string RawUrl {
499                         get { return raw_url; }
500                 }
501
502                 public IPEndPoint RemoteEndPoint {
503                         get { return context.Connection.RemoteEndPoint; }
504                 }
505
506                 [MonoTODO ("Always returns Guid.Empty")]
507                 public Guid RequestTraceIdentifier {
508                         get { return Guid.Empty; }
509                 }
510
511                 public Uri Url {
512                         get { return url; }
513                 }
514
515                 public Uri UrlReferrer {
516                         get { return referrer; }
517                 }
518
519                 public string UserAgent {
520                         get { return headers ["user-agent"]; }
521                 }
522
523                 public string UserHostAddress {
524                         get { return LocalEndPoint.ToString (); }
525                 }
526
527                 public string UserHostName {
528                         get { return headers ["host"]; }
529                 }
530
531                 public string [] UserLanguages {
532                         get { return user_languages; }
533                 }
534
535                 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
536                 {
537                         if (gcc_delegate == null)
538                                 gcc_delegate = new GCCDelegate (GetClientCertificate);
539                         return gcc_delegate.BeginInvoke (requestCallback, state);
540                 }
541
542                 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
543                 {
544                         if (asyncResult == null)
545                                 throw new ArgumentNullException ("asyncResult");
546
547                         if (gcc_delegate == null)
548                                 throw new InvalidOperationException ();
549
550                         return gcc_delegate.EndInvoke (asyncResult);
551                 }
552
553                 public X509Certificate2 GetClientCertificate ()
554                 {
555                         return context.Connection.ClientCertificate;
556                 }
557
558                 [MonoTODO]
559                 public string ServiceName {
560                         get {
561                                 return null;
562                         }
563                 }
564                 
565                 public TransportContext TransportContext {
566                         get {
567                                 return new Context ();
568                         }
569                 }
570                 
571                 [MonoTODO]
572                 public bool IsWebSocketRequest {
573                         get {
574                                 return false;
575                         }
576                 }
577
578                 public Task<X509Certificate2> GetClientCertificateAsync ()
579                 {
580                         return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);
581                 }
582         }
583 }
584