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