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