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