Merge branch 'sgen-disable-gc'
[mono.git] / mcs / class / System / System.Net / HttpListenerRequest.cs
1 //
2 // System.Net.HttpListenerRequest
3 //
4 // Author:
5 //      Gonzalo Paniagua Javier (gonzalo@novell.com)
6 //
7 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28
29 #if NET_2_0 && SECURITY_DEP
30
31 using System.Collections;
32 using System.Collections.Specialized;
33 using System.Globalization;
34 using System.IO;
35 using System.Security.Cryptography.X509Certificates;
36 using System.Text;
37 namespace System.Net {
38         public sealed class HttpListenerRequest
39         {
40                 string [] accept_types;
41 //              int client_cert_error;
42 //              bool no_get_certificate;
43                 Encoding content_encoding;
44                 long content_length;
45                 bool cl_set;
46                 CookieCollection cookies;
47                 WebHeaderCollection headers;
48                 string method;
49                 Stream input_stream;
50                 Version version;
51                 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
52                 string raw_url;
53                 Uri url;
54                 Uri referrer;
55                 string [] user_languages;
56                 HttpListenerContext context;
57                 bool is_chunked;
58                 bool ka_set;
59                 bool keep_alive;
60                 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
61
62                 internal HttpListenerRequest (HttpListenerContext context)
63                 {
64                         this.context = context;
65                         headers = new WebHeaderCollection ();
66                         version = HttpVersion.Version10;
67                 }
68
69                 static char [] separators = new char [] { ' ' };
70
71                 internal void SetRequestLine (string req)
72                 {
73                         string [] parts = req.Split (separators, 3);
74                         if (parts.Length != 3) {
75                                 context.ErrorMessage = "Invalid request line (parts).";
76                                 return;
77                         }
78
79                         method = parts [0];
80                         foreach (char c in method){
81                                 int ic = (int) c;
82
83                                 if ((ic >= 'A' && ic <= 'Z') ||
84                                     (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
85                                      c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
86                                      c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
87                                      c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
88                                         continue;
89
90                                 context.ErrorMessage = "(Invalid verb)";
91                                 return;
92                         }
93
94                         raw_url = parts [1];
95                         if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
96                                 context.ErrorMessage = "Invalid request line (version).";
97                                 return;
98                         }
99
100                         try {
101                                 version = new Version (parts [2].Substring (5));
102                                 if (version.Major < 1)
103                                         throw new Exception ();
104                         } catch {
105                                 context.ErrorMessage = "Invalid request line (version).";
106                                 return;
107                         }
108                 }
109
110                 void CreateQueryString (string query)
111                 {
112                         if (query == null || query.Length == 0) {
113                                 query_string = new NameValueCollection (1);
114                                 return;
115                         }
116
117                         query_string = new NameValueCollection ();
118                         if (query [0] == '?')
119                                 query = query.Substring (1);
120                         string [] components = query.Split ('&');
121                         foreach (string kv in components) {
122                                 int pos = kv.IndexOf ('=');
123                                 if (pos == -1) {
124                                         query_string.Add (null, HttpUtility.UrlDecode (kv));
125                                 } else {
126                                         string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
127                                         string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
128                                         
129                                         query_string.Add (key, val);
130                                 }
131                         }
132                 }
133
134                 internal void FinishInitialization ()
135                 {
136                         string host = UserHostName;
137                         if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
138                                 context.ErrorMessage = "Invalid host name";
139                                 return;
140                         }
141
142                         string path;
143                         Uri raw_uri = null;
144                         if (Uri.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
145                                 path = raw_uri.PathAndQuery;
146                         else
147                                 path = raw_url;
148
149                         if ((host == null || host.Length == 0))
150                                 host = UserHostAddress;
151
152                         if (raw_uri != null)
153                                 host = raw_uri.Host;
154         
155                         int colon = host.IndexOf (':');
156                         if (colon >= 0)
157                                 host = host.Substring (0, colon);
158
159                         string base_uri = String.Format ("{0}://{1}:{2}",
160                                                                 (IsSecureConnection) ? "https" : "http",
161                                                                 host, LocalEndPoint.Port);
162
163                         if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
164                                 context.ErrorMessage = "Invalid url: " + base_uri + path;
165                                 return;
166                         }
167
168                         CreateQueryString (url.Query);
169
170                         if (version >= HttpVersion.Version11) {
171                                 string t_encoding = Headers ["Transfer-Encoding"];
172                                 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
173                                 // 'identity' is not valid!
174                                 if (t_encoding != null && !is_chunked) {
175                                         context.Connection.SendError (null, 501);
176                                         return;
177                                 }
178                         }
179
180                         if (!is_chunked && !cl_set) {
181                                 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
182                                     String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
183                                         context.Connection.SendError (null, 411);
184                                         return;
185                                 }
186                         }
187
188                         if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
189                                 ResponseStream output = context.Connection.GetResponseStream ();
190                                 output.InternalWrite (_100continue, 0, _100continue.Length);
191                         }
192                 }
193
194                 internal static string Unquote (String str) {
195                         int start = str.IndexOf ('\"');
196                         int end = str.LastIndexOf ('\"');
197                         if (start >= 0 && end >=0)
198                                 str = str.Substring (start + 1, end - 1);
199                         return str.Trim ();
200                 }
201
202                 internal void AddHeader (string header)
203                 {
204                         int colon = header.IndexOf (':');
205                         if (colon == -1 || colon == 0) {
206                                 context.ErrorMessage = "Bad Request";
207                                 context.ErrorStatus = 400;
208                                 return;
209                         }
210
211                         string name = header.Substring (0, colon).Trim ();
212                         string val = header.Substring (colon + 1).Trim ();
213                         string lower = name.ToLower (CultureInfo.InvariantCulture);
214                         headers.SetInternal (name, val);
215                         switch (lower) {
216                                 case "accept-language":
217                                         user_languages = val.Split (','); // yes, only split with a ','
218                                         break;
219                                 case "accept":
220                                         accept_types = val.Split (','); // yes, only split with a ','
221                                         break;
222                                 case "content-length":
223                                         try {
224                                                 //TODO: max. content_length?
225                                                 content_length = Int64.Parse (val.Trim ());
226                                                 if (content_length < 0)
227                                                         context.ErrorMessage = "Invalid Content-Length.";
228                                                 cl_set = true;
229                                         } catch {
230                                                 context.ErrorMessage = "Invalid Content-Length.";
231                                         }
232
233                                         break;
234                                 case "referer":
235                                         try {
236                                                 referrer = new Uri (val);
237                                         } catch {
238                                                 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
239                                         }
240                                         break;
241                                 case "cookie":
242                                         if (cookies == null)
243                                                 cookies = new CookieCollection();
244
245                                         string[] cookieStrings = val.Split(new char[] {',', ';'});
246                                         Cookie current = null;
247                                         int version = 0;
248                                         foreach (string cookieString in cookieStrings) {
249                                                 string str = cookieString.Trim ();
250                                                 if (str.Length == 0)
251                                                         continue;
252                                                 if (str.StartsWith ("$Version")) {
253                                                         version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
254                                                 } else if (str.StartsWith ("$Path")) {
255                                                         if (current != null)
256                                                                 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
257                                                 } else if (str.StartsWith ("$Domain")) {
258                                                         if (current != null)
259                                                                 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
260                                                 } else if (str.StartsWith ("$Port")) {
261                                                         if (current != null)
262                                                                 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
263                                                 } else {
264                                                         if (current != null) {
265                                                                 cookies.Add (current);
266                                                         }
267                                                         current = new Cookie ();
268                                                         int idx = str.IndexOf ('=');
269                                                         if (idx > 0) {
270                                                                 current.Name = str.Substring (0, idx).Trim ();
271                                                                 current.Value =  str.Substring (idx + 1).Trim ();
272                                                         } else {
273                                                                 current.Name = str.Trim ();
274                                                                 current.Value = String.Empty;
275                                                         }
276                                                         current.Version = version;
277                                                 }
278                                         }
279                                         if (current != null) {
280                                                 cookies.Add (current);
281                                         }
282                                         break;
283                         }
284                 }
285
286                 // returns true is the stream could be reused.
287                 internal bool FlushInput ()
288                 {
289                         if (!HasEntityBody)
290                                 return true;
291
292                         int length = 2048;
293                         if (content_length > 0)
294                                 length = (int) Math.Min (content_length, (long) length);
295
296                         byte [] bytes = new byte [length];
297                         while (true) {
298                                 // TODO: test if MS has a timeout when doing this
299                                 try {
300                                         IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
301                                         if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100))
302                                                 return false;
303                                         if (InputStream.EndRead (ares) <= 0)
304                                                 return true;
305                                 } catch {
306                                         return false;
307                                 }
308                         }
309                 }
310
311                 public string [] AcceptTypes {
312                         get { return accept_types; }
313                 }
314
315                 [MonoTODO ("Always returns 0")]
316                 public int ClientCertificateError {
317                         get {
318 /*                              
319                                 if (no_get_certificate)
320                                         throw new InvalidOperationException (
321                                                 "Call GetClientCertificate() before calling this method.");
322                                 return client_cert_error;
323 */
324                                 return 0;
325                         }
326                 }
327
328                 public Encoding ContentEncoding {
329                         get {
330                                 if (content_encoding == null)
331                                         content_encoding = Encoding.Default;
332                                 return content_encoding;
333                         }
334                 }
335
336                 public long ContentLength64 {
337                         get { return content_length; }
338                 }
339
340                 public string ContentType {
341                         get { return headers ["content-type"]; }
342                 }
343
344                 public CookieCollection Cookies {
345                         get {
346                                 // TODO: check if the collection is read-only
347                                 if (cookies == null)
348                                         cookies = new CookieCollection ();
349                                 return cookies;
350                         }
351                 }
352
353                 public bool HasEntityBody {
354                         get { return (content_length > 0 || is_chunked); }
355                 }
356
357                 public NameValueCollection Headers {
358                         get { return headers; }
359                 }
360
361                 public string HttpMethod {
362                         get { return method; }
363                 }
364
365                 public Stream InputStream {
366                         get {
367                                 if (input_stream == null) {
368                                         if (is_chunked || content_length > 0)
369                                                 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
370                                         else
371                                                 input_stream = Stream.Null;
372                                 }
373
374                                 return input_stream;
375                         }
376                 }
377
378                 [MonoTODO ("Always returns false")]
379                 public bool IsAuthenticated {
380                         get { return false; }
381                 }
382
383                 public bool IsLocal {
384                         get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
385                 }
386
387                 public bool IsSecureConnection {
388                         get { return context.Connection.IsSecure; } 
389                 }
390
391                 public bool KeepAlive {
392                         get {
393                                 if (ka_set)
394                                         return keep_alive;
395
396                                 ka_set = true;
397                                 // 1. Connection header
398                                 // 2. Protocol (1.1 == keep-alive by default)
399                                 // 3. Keep-Alive header
400                                 string cnc = headers ["Connection"];
401                                 if (!String.IsNullOrEmpty (cnc)) {
402                                         keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
403                                 } else if (version == HttpVersion.Version11) {
404                                         keep_alive = true;
405                                 } else {
406                                         cnc = headers ["keep-alive"];
407                                         if (!String.IsNullOrEmpty (cnc))
408                                                 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
409                                 }
410                                 return keep_alive;
411                         }
412                 }
413
414                 public IPEndPoint LocalEndPoint {
415                         get { return context.Connection.LocalEndPoint; }
416                 }
417
418                 public Version ProtocolVersion {
419                         get { return version; }
420                 }
421
422                 public NameValueCollection QueryString {
423                         get { return query_string; }
424                 }
425
426                 public string RawUrl {
427                         get { return raw_url; }
428                 }
429
430                 public IPEndPoint RemoteEndPoint {
431                         get { return context.Connection.RemoteEndPoint; }
432                 }
433
434                 [MonoTODO ("Always returns Guid.Empty")]
435                 public Guid RequestTraceIdentifier {
436                         get { return Guid.Empty; }
437                 }
438
439                 public Uri Url {
440                         get { return url; }
441                 }
442
443                 public Uri UrlReferrer {
444                         get { return referrer; }
445                 }
446
447                 public string UserAgent {
448                         get { return headers ["user-agent"]; }
449                 }
450
451                 public string UserHostAddress {
452                         get { return LocalEndPoint.ToString (); }
453                 }
454
455                 public string UserHostName {
456                         get { return headers ["host"]; }
457                 }
458
459                 public string [] UserLanguages {
460                         get { return user_languages; }
461                 }
462
463                 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
464                 {
465                         return null;
466                 }
467 #if SECURITY_DEP
468                 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
469                 {
470                         return null;
471                         // set no_client_certificate once done.
472                 }
473
474                 public X509Certificate2 GetClientCertificate ()
475                 {
476                         // set no_client_certificate once done.
477
478                         // InvalidOp if call in progress.
479                         return null;
480                 }
481 #endif
482         }
483 }
484 #endif
485