Merge pull request #2227 from esdrubal/tzparse
[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 #if SECURITY_DEP
32
33 using System.Collections;
34 using System.Collections.Specialized;
35 using System.Globalization;
36 using System.IO;
37 using System.Security.Cryptography.X509Certificates;
38 using System.Text;
39 using System.Security.Authentication.ExtendedProtection;
40 using System.Threading.Tasks;
41
42 namespace System.Net {
43         public sealed class HttpListenerRequest
44         {
45                 class Context : TransportContext
46                 {
47                         public override ChannelBinding GetChannelBinding (ChannelBindingKind kind)
48                         {
49                                 throw new NotImplementedException ();
50                         }
51                 }
52
53                 string [] accept_types;
54                 Encoding content_encoding;
55                 long content_length;
56                 bool cl_set;
57                 CookieCollection cookies;
58                 WebHeaderCollection headers;
59                 string method;
60                 Stream input_stream;
61                 Version version;
62                 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
63                 string raw_url;
64                 Uri url;
65                 Uri referrer;
66                 string [] user_languages;
67                 HttpListenerContext context;
68                 bool is_chunked;
69                 bool ka_set;
70                 bool keep_alive;
71                 delegate X509Certificate2 GCCDelegate ();
72                 GCCDelegate gcc_delegate;
73
74                 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
75
76                 internal HttpListenerRequest (HttpListenerContext context)
77                 {
78                         this.context = context;
79                         headers = new WebHeaderCollection ();
80                         version = HttpVersion.Version10;
81                 }
82
83                 static char [] separators = new char [] { ' ' };
84
85                 internal void SetRequestLine (string req)
86                 {
87                         string [] parts = req.Split (separators, 3);
88                         if (parts.Length != 3) {
89                                 context.ErrorMessage = "Invalid request line (parts).";
90                                 return;
91                         }
92
93                         method = parts [0];
94                         foreach (char c in method){
95                                 int ic = (int) c;
96
97                                 if ((ic >= 'A' && ic <= 'Z') ||
98                                     (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
99                                      c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
100                                      c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
101                                      c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
102                                         continue;
103
104                                 context.ErrorMessage = "(Invalid verb)";
105                                 return;
106                         }
107
108                         raw_url = parts [1];
109                         if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
110                                 context.ErrorMessage = "Invalid request line (version).";
111                                 return;
112                         }
113
114                         try {
115                                 version = new Version (parts [2].Substring (5));
116                                 if (version.Major < 1)
117                                         throw new Exception ();
118                         } catch {
119                                 context.ErrorMessage = "Invalid request line (version).";
120                                 return;
121                         }
122                 }
123
124                 void CreateQueryString (string query)
125                 {
126                         if (query == null || query.Length == 0) {
127                                 query_string = new NameValueCollection (1);
128                                 return;
129                         }
130
131                         query_string = new NameValueCollection ();
132                         if (query [0] == '?')
133                                 query = query.Substring (1);
134                         string [] components = query.Split ('&');
135                         foreach (string kv in components) {
136                                 int pos = kv.IndexOf ('=');
137                                 if (pos == -1) {
138                                         query_string.Add (null, WebUtility.UrlDecode (kv));
139                                 } else {
140                                         string key = WebUtility.UrlDecode (kv.Substring (0, pos));
141                                         string val = WebUtility.UrlDecode (kv.Substring (pos + 1));
142                                         
143                                         query_string.Add (key, val);
144                                 }
145                         }
146                 }
147
148                 internal void FinishInitialization ()
149                 {
150                         string host = UserHostName;
151                         if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
152                                 context.ErrorMessage = "Invalid host name";
153                                 return;
154                         }
155
156                         string path;
157                         Uri raw_uri = null;
158                         if (Uri.MaybeUri (raw_url.ToLowerInvariant ()) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
159                                 path = raw_uri.PathAndQuery;
160                         else
161                                 path = raw_url;
162
163                         if ((host == null || host.Length == 0))
164                                 host = UserHostAddress;
165
166                         if (raw_uri != null)
167                                 host = raw_uri.Host;
168         
169                         int colon = host.IndexOf (':');
170                         if (colon >= 0)
171                                 host = host.Substring (0, colon);
172
173                         string base_uri = String.Format ("{0}://{1}:{2}",
174                                                                 (IsSecureConnection) ? "https" : "http",
175                                                                 host, LocalEndPoint.Port);
176
177                         if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
178                                 context.ErrorMessage = "Invalid url: " + base_uri + path;
179                                 return;
180                         }
181
182                         CreateQueryString (url.Query);
183
184                         // Use reference source HttpListenerRequestUriBuilder to process url.
185                         // Fixes #29927
186                         url = HttpListenerRequestUriBuilder.GetRequestUri (raw_url, url.Scheme,
187                                                                 url.Authority, url.LocalPath, url.Query);
188
189                         if (version >= HttpVersion.Version11) {
190                                 string t_encoding = Headers ["Transfer-Encoding"];
191                                 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
192                                 // 'identity' is not valid!
193                                 if (t_encoding != null && !is_chunked) {
194                                         context.Connection.SendError (null, 501);
195                                         return;
196                                 }
197                         }
198
199                         if (!is_chunked && !cl_set) {
200                                 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
201                                     String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
202                                         context.Connection.SendError (null, 411);
203                                         return;
204                                 }
205                         }
206
207                         if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
208                                 ResponseStream output = context.Connection.GetResponseStream ();
209                                 output.InternalWrite (_100continue, 0, _100continue.Length);
210                         }
211                 }
212
213                 internal static string Unquote (String str) {
214                         int start = str.IndexOf ('\"');
215                         int end = str.LastIndexOf ('\"');
216                         if (start >= 0 && end >=0)
217                                 str = str.Substring (start + 1, end - 1);
218                         return str.Trim ();
219                 }
220
221                 internal void AddHeader (string header)
222                 {
223                         int colon = header.IndexOf (':');
224                         if (colon == -1 || colon == 0) {
225                                 context.ErrorMessage = "Bad Request";
226                                 context.ErrorStatus = 400;
227                                 return;
228                         }
229
230                         string name = header.Substring (0, colon).Trim ();
231                         string val = header.Substring (colon + 1).Trim ();
232                         string lower = name.ToLower (CultureInfo.InvariantCulture);
233                         headers.SetInternal (name, val);
234                         switch (lower) {
235                                 case "accept-language":
236                                         user_languages = val.Split (','); // yes, only split with a ','
237                                         break;
238                                 case "accept":
239                                         accept_types = val.Split (','); // yes, only split with a ','
240                                         break;
241                                 case "content-length":
242                                         try {
243                                                 //TODO: max. content_length?
244                                                 content_length = Int64.Parse (val.Trim ());
245                                                 if (content_length < 0)
246                                                         context.ErrorMessage = "Invalid Content-Length.";
247                                                 cl_set = true;
248                                         } catch {
249                                                 context.ErrorMessage = "Invalid Content-Length.";
250                                         }
251
252                                         break;
253                                 case "referer":
254                                         try {
255                                                 referrer = new Uri (val);
256                                         } catch {
257                                                 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
258                                         }
259                                         break;
260                                 case "cookie":
261                                         if (cookies == null)
262                                                 cookies = new CookieCollection();
263
264                                         string[] cookieStrings = val.Split(new char[] {',', ';'});
265                                         Cookie current = null;
266                                         int version = 0;
267                                         foreach (string cookieString in cookieStrings) {
268                                                 string str = cookieString.Trim ();
269                                                 if (str.Length == 0)
270                                                         continue;
271                                                 if (str.StartsWith ("$Version")) {
272                                                         version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
273                                                 } else if (str.StartsWith ("$Path")) {
274                                                         if (current != null)
275                                                                 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
276                                                 } else if (str.StartsWith ("$Domain")) {
277                                                         if (current != null)
278                                                                 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
279                                                 } else if (str.StartsWith ("$Port")) {
280                                                         if (current != null)
281                                                                 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
282                                                 } else {
283                                                         if (current != null) {
284                                                                 cookies.Add (current);
285                                                         }
286                                                         current = new Cookie ();
287                                                         int idx = str.IndexOf ('=');
288                                                         if (idx > 0) {
289                                                                 current.Name = str.Substring (0, idx).Trim ();
290                                                                 current.Value =  str.Substring (idx + 1).Trim ();
291                                                         } else {
292                                                                 current.Name = str.Trim ();
293                                                                 current.Value = String.Empty;
294                                                         }
295                                                         current.Version = version;
296                                                 }
297                                         }
298                                         if (current != null) {
299                                                 cookies.Add (current);
300                                         }
301                                         break;
302                         }
303                 }
304
305                 // returns true is the stream could be reused.
306                 internal bool FlushInput ()
307                 {
308                         if (!HasEntityBody)
309                                 return true;
310
311                         int length = 2048;
312                         if (content_length > 0)
313                                 length = (int) Math.Min (content_length, (long) length);
314
315                         byte [] bytes = new byte [length];
316                         while (true) {
317                                 // TODO: test if MS has a timeout when doing this
318                                 try {
319                                         IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
320                                         if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (1000))
321                                                 return false;
322                                         if (InputStream.EndRead (ares) <= 0)
323                                                 return true;
324                                 } catch (ObjectDisposedException e) {
325                                         input_stream = null;
326                                         return true;
327                                 } catch {
328                                         return false;
329                                 }
330                         }
331                 }
332
333                 public string [] AcceptTypes {
334                         get { return accept_types; }
335                 }
336
337                 public int ClientCertificateError {
338                         get {
339                                 HttpConnection cnc = context.Connection;
340                                 if (cnc.ClientCertificate == null)
341                                         throw new InvalidOperationException ("No client certificate");
342                                 int [] errors = cnc.ClientCertificateErrors;
343                                 if (errors != null && errors.Length > 0)
344                                         return errors [0];
345                                 return 0;
346                         }
347                 }
348
349                 public Encoding ContentEncoding {
350                         get {
351                                 if (content_encoding == null)
352                                         content_encoding = Encoding.Default;
353                                 return content_encoding;
354                         }
355                 }
356
357                 public long ContentLength64 {
358                         get { return content_length; }
359                 }
360
361                 public string ContentType {
362                         get { return headers ["content-type"]; }
363                 }
364
365                 public CookieCollection Cookies {
366                         get {
367                                 // TODO: check if the collection is read-only
368                                 if (cookies == null)
369                                         cookies = new CookieCollection ();
370                                 return cookies;
371                         }
372                 }
373
374                 public bool HasEntityBody {
375                         get { return (content_length > 0 || is_chunked); }
376                 }
377
378                 public NameValueCollection Headers {
379                         get { return headers; }
380                 }
381
382                 public string HttpMethod {
383                         get { return method; }
384                 }
385
386                 public Stream InputStream {
387                         get {
388                                 if (input_stream == null) {
389                                         if (is_chunked || content_length > 0)
390                                                 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
391                                         else
392                                                 input_stream = Stream.Null;
393                                 }
394
395                                 return input_stream;
396                         }
397                 }
398
399                 [MonoTODO ("Always returns false")]
400                 public bool IsAuthenticated {
401                         get { return false; }
402                 }
403
404                 public bool IsLocal {
405                         get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
406                 }
407
408                 public bool IsSecureConnection {
409                         get { return context.Connection.IsSecure; } 
410                 }
411
412                 public bool KeepAlive {
413                         get {
414                                 if (ka_set)
415                                         return keep_alive;
416
417                                 ka_set = true;
418                                 // 1. Connection header
419                                 // 2. Protocol (1.1 == keep-alive by default)
420                                 // 3. Keep-Alive header
421                                 string cnc = headers ["Connection"];
422                                 if (!String.IsNullOrEmpty (cnc)) {
423                                         keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
424                                 } else if (version == HttpVersion.Version11) {
425                                         keep_alive = true;
426                                 } else {
427                                         cnc = headers ["keep-alive"];
428                                         if (!String.IsNullOrEmpty (cnc))
429                                                 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
430                                 }
431                                 return keep_alive;
432                         }
433                 }
434
435                 public IPEndPoint LocalEndPoint {
436                         get { return context.Connection.LocalEndPoint; }
437                 }
438
439                 public Version ProtocolVersion {
440                         get { return version; }
441                 }
442
443                 public NameValueCollection QueryString {
444                         get { return query_string; }
445                 }
446
447                 public string RawUrl {
448                         get { return raw_url; }
449                 }
450
451                 public IPEndPoint RemoteEndPoint {
452                         get { return context.Connection.RemoteEndPoint; }
453                 }
454
455                 [MonoTODO ("Always returns Guid.Empty")]
456                 public Guid RequestTraceIdentifier {
457                         get { return Guid.Empty; }
458                 }
459
460                 public Uri Url {
461                         get { return url; }
462                 }
463
464                 public Uri UrlReferrer {
465                         get { return referrer; }
466                 }
467
468                 public string UserAgent {
469                         get { return headers ["user-agent"]; }
470                 }
471
472                 public string UserHostAddress {
473                         get { return LocalEndPoint.ToString (); }
474                 }
475
476                 public string UserHostName {
477                         get { return headers ["host"]; }
478                 }
479
480                 public string [] UserLanguages {
481                         get { return user_languages; }
482                 }
483
484                 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
485                 {
486                         if (gcc_delegate == null)
487                                 gcc_delegate = new GCCDelegate (GetClientCertificate);
488                         return gcc_delegate.BeginInvoke (requestCallback, state);
489                 }
490
491                 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
492                 {
493                         if (asyncResult == null)
494                                 throw new ArgumentNullException ("asyncResult");
495
496                         if (gcc_delegate == null)
497                                 throw new InvalidOperationException ();
498
499                         return gcc_delegate.EndInvoke (asyncResult);
500                 }
501
502                 public X509Certificate2 GetClientCertificate ()
503                 {
504                         return context.Connection.ClientCertificate;
505                 }
506
507                 [MonoTODO]
508                 public string ServiceName {
509                         get {
510                                 return null;
511                         }
512                 }
513                 
514                 public TransportContext TransportContext {
515                         get {
516                                 return new Context ();
517                         }
518                 }
519                 
520                 [MonoTODO]
521                 public bool IsWebSocketRequest {
522                         get {
523                                 return false;
524                         }
525                 }
526
527                 public Task<X509Certificate2> GetClientCertificateAsync ()
528                 {
529                         return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);
530                 }
531         }
532 }
533 #endif
534