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