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