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