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