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