Merge pull request #1458 from BrzVlad/feature-fat-cas
[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) && 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                         if (version >= HttpVersion.Version11) {
192                                 string t_encoding = Headers ["Transfer-Encoding"];
193                                 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
194                                 // 'identity' is not valid!
195                                 if (t_encoding != null && !is_chunked) {
196                                         context.Connection.SendError (null, 501);
197                                         return;
198                                 }
199                         }
200
201                         if (!is_chunked && !cl_set) {
202                                 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
203                                     String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
204                                         context.Connection.SendError (null, 411);
205                                         return;
206                                 }
207                         }
208
209                         if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
210                                 ResponseStream output = context.Connection.GetResponseStream ();
211                                 output.InternalWrite (_100continue, 0, _100continue.Length);
212                         }
213                 }
214
215                 internal static string Unquote (String str) {
216                         int start = str.IndexOf ('\"');
217                         int end = str.LastIndexOf ('\"');
218                         if (start >= 0 && end >=0)
219                                 str = str.Substring (start + 1, end - 1);
220                         return str.Trim ();
221                 }
222
223                 internal void AddHeader (string header)
224                 {
225                         int colon = header.IndexOf (':');
226                         if (colon == -1 || colon == 0) {
227                                 context.ErrorMessage = "Bad Request";
228                                 context.ErrorStatus = 400;
229                                 return;
230                         }
231
232                         string name = header.Substring (0, colon).Trim ();
233                         string val = header.Substring (colon + 1).Trim ();
234                         string lower = name.ToLower (CultureInfo.InvariantCulture);
235                         headers.SetInternal (name, val);
236                         switch (lower) {
237                                 case "accept-language":
238                                         user_languages = val.Split (','); // yes, only split with a ','
239                                         break;
240                                 case "accept":
241                                         accept_types = val.Split (','); // yes, only split with a ','
242                                         break;
243                                 case "content-length":
244                                         try {
245                                                 //TODO: max. content_length?
246                                                 content_length = Int64.Parse (val.Trim ());
247                                                 if (content_length < 0)
248                                                         context.ErrorMessage = "Invalid Content-Length.";
249                                                 cl_set = true;
250                                         } catch {
251                                                 context.ErrorMessage = "Invalid Content-Length.";
252                                         }
253
254                                         break;
255                                 case "referer":
256                                         try {
257                                                 referrer = new Uri (val);
258                                         } catch {
259                                                 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
260                                         }
261                                         break;
262                                 case "cookie":
263                                         if (cookies == null)
264                                                 cookies = new CookieCollection();
265
266                                         string[] cookieStrings = val.Split(new char[] {',', ';'});
267                                         Cookie current = null;
268                                         int version = 0;
269                                         foreach (string cookieString in cookieStrings) {
270                                                 string str = cookieString.Trim ();
271                                                 if (str.Length == 0)
272                                                         continue;
273                                                 if (str.StartsWith ("$Version")) {
274                                                         version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
275                                                 } else if (str.StartsWith ("$Path")) {
276                                                         if (current != null)
277                                                                 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
278                                                 } else if (str.StartsWith ("$Domain")) {
279                                                         if (current != null)
280                                                                 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
281                                                 } else if (str.StartsWith ("$Port")) {
282                                                         if (current != null)
283                                                                 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
284                                                 } else {
285                                                         if (current != null) {
286                                                                 cookies.Add (current);
287                                                         }
288                                                         current = new Cookie ();
289                                                         int idx = str.IndexOf ('=');
290                                                         if (idx > 0) {
291                                                                 current.Name = str.Substring (0, idx).Trim ();
292                                                                 current.Value =  str.Substring (idx + 1).Trim ();
293                                                         } else {
294                                                                 current.Name = str.Trim ();
295                                                                 current.Value = String.Empty;
296                                                         }
297                                                         current.Version = version;
298                                                 }
299                                         }
300                                         if (current != null) {
301                                                 cookies.Add (current);
302                                         }
303                                         break;
304                         }
305                 }
306
307                 // returns true is the stream could be reused.
308                 internal bool FlushInput ()
309                 {
310                         if (!HasEntityBody)
311                                 return true;
312
313                         int length = 2048;
314                         if (content_length > 0)
315                                 length = (int) Math.Min (content_length, (long) length);
316
317                         byte [] bytes = new byte [length];
318                         while (true) {
319                                 // TODO: test if MS has a timeout when doing this
320                                 try {
321                                         IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
322                                         if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (1000))
323                                                 return false;
324                                         if (InputStream.EndRead (ares) <= 0)
325                                                 return true;
326                                 } catch (ObjectDisposedException e) {
327                                         input_stream = null;
328                                         return true;
329                                 } catch {
330                                         return false;
331                                 }
332                         }
333                 }
334
335                 public string [] AcceptTypes {
336                         get { return accept_types; }
337                 }
338
339                 public int ClientCertificateError {
340                         get {
341                                 HttpConnection cnc = context.Connection;
342                                 if (cnc.ClientCertificate == null)
343                                         throw new InvalidOperationException ("No client certificate");
344                                 int [] errors = cnc.ClientCertificateErrors;
345                                 if (errors != null && errors.Length > 0)
346                                         return errors [0];
347                                 return 0;
348                         }
349                 }
350
351                 public Encoding ContentEncoding {
352                         get {
353                                 if (content_encoding == null)
354                                         content_encoding = Encoding.Default;
355                                 return content_encoding;
356                         }
357                 }
358
359                 public long ContentLength64 {
360                         get { return content_length; }
361                 }
362
363                 public string ContentType {
364                         get { return headers ["content-type"]; }
365                 }
366
367                 public CookieCollection Cookies {
368                         get {
369                                 // TODO: check if the collection is read-only
370                                 if (cookies == null)
371                                         cookies = new CookieCollection ();
372                                 return cookies;
373                         }
374                 }
375
376                 public bool HasEntityBody {
377                         get { return (content_length > 0 || is_chunked); }
378                 }
379
380                 public NameValueCollection Headers {
381                         get { return headers; }
382                 }
383
384                 public string HttpMethod {
385                         get { return method; }
386                 }
387
388                 public Stream InputStream {
389                         get {
390                                 if (input_stream == null) {
391                                         if (is_chunked || content_length > 0)
392                                                 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
393                                         else
394                                                 input_stream = Stream.Null;
395                                 }
396
397                                 return input_stream;
398                         }
399                 }
400
401                 [MonoTODO ("Always returns false")]
402                 public bool IsAuthenticated {
403                         get { return false; }
404                 }
405
406                 public bool IsLocal {
407                         get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
408                 }
409
410                 public bool IsSecureConnection {
411                         get { return context.Connection.IsSecure; } 
412                 }
413
414                 public bool KeepAlive {
415                         get {
416                                 if (ka_set)
417                                         return keep_alive;
418
419                                 ka_set = true;
420                                 // 1. Connection header
421                                 // 2. Protocol (1.1 == keep-alive by default)
422                                 // 3. Keep-Alive header
423                                 string cnc = headers ["Connection"];
424                                 if (!String.IsNullOrEmpty (cnc)) {
425                                         keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
426                                 } else if (version == HttpVersion.Version11) {
427                                         keep_alive = true;
428                                 } else {
429                                         cnc = headers ["keep-alive"];
430                                         if (!String.IsNullOrEmpty (cnc))
431                                                 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
432                                 }
433                                 return keep_alive;
434                         }
435                 }
436
437                 public IPEndPoint LocalEndPoint {
438                         get { return context.Connection.LocalEndPoint; }
439                 }
440
441                 public Version ProtocolVersion {
442                         get { return version; }
443                 }
444
445                 public NameValueCollection QueryString {
446                         get { return query_string; }
447                 }
448
449                 public string RawUrl {
450                         get { return raw_url; }
451                 }
452
453                 public IPEndPoint RemoteEndPoint {
454                         get { return context.Connection.RemoteEndPoint; }
455                 }
456
457                 [MonoTODO ("Always returns Guid.Empty")]
458                 public Guid RequestTraceIdentifier {
459                         get { return Guid.Empty; }
460                 }
461
462                 public Uri Url {
463                         get { return url; }
464                 }
465
466                 public Uri UrlReferrer {
467                         get { return referrer; }
468                 }
469
470                 public string UserAgent {
471                         get { return headers ["user-agent"]; }
472                 }
473
474                 public string UserHostAddress {
475                         get { return LocalEndPoint.ToString (); }
476                 }
477
478                 public string UserHostName {
479                         get { return headers ["host"]; }
480                 }
481
482                 public string [] UserLanguages {
483                         get { return user_languages; }
484                 }
485
486                 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
487                 {
488                         if (gcc_delegate == null)
489                                 gcc_delegate = new GCCDelegate (GetClientCertificate);
490                         return gcc_delegate.BeginInvoke (requestCallback, state);
491                 }
492
493                 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
494                 {
495                         if (asyncResult == null)
496                                 throw new ArgumentNullException ("asyncResult");
497
498                         if (gcc_delegate == null)
499                                 throw new InvalidOperationException ();
500
501                         return gcc_delegate.EndInvoke (asyncResult);
502                 }
503
504                 public X509Certificate2 GetClientCertificate ()
505                 {
506                         return context.Connection.ClientCertificate;
507                 }
508
509                 [MonoTODO]
510                 public string ServiceName {
511                         get {
512                                 return null;
513                         }
514                 }
515                 
516                 public TransportContext TransportContext {
517                         get {
518                                 return new Context ();
519                         }
520                 }
521                 
522                 [MonoTODO]
523                 public bool IsWebSocketRequest {
524                         get {
525                                 return false;
526                         }
527                 }
528
529                 public Task<X509Certificate2> GetClientCertificateAsync ()
530                 {
531                         return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);
532                 }
533         }
534 }
535 #endif
536