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