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