2007-09-28 Marek Habersack <mhabersack@novell.com>
[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                 Encoding content_encoding;
43                 long content_length;
44                 bool cl_set;
45                 CookieCollection cookies;
46                 WebHeaderCollection headers;
47                 string method;
48                 Stream input_stream;
49                 bool is_authenticated;
50                 Version version;
51                 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
52                 string raw_url;
53                 Guid identifier;
54                 Uri url;
55                 Uri referrer;
56                 string [] user_languages;
57                 bool no_get_certificate;
58                 HttpListenerContext context;
59                 bool is_chunked;
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                         input_stream = Stream.Null;
67                 }
68
69                 static char [] separators = new char [] { ' ' };
70
71 #if false
72                 static readonly string [] methods = new string [] { "GET", "POST", "HEAD",
73                                                                 "PUT", "CONNECT", "MKCOL" };
74 #endif
75                 internal void SetRequestLine (string req)
76                 {
77                         string [] parts = req.Split (separators, 3);
78                         if (parts.Length != 3) {
79                                 context.ErrorMessage = "Invalid request line (parts).";
80                                 return;
81                         }
82
83                         method = parts [0].ToUpperInvariant ();
84                         foreach (char c in method){
85                                 int ic = (int) c;
86
87                                 if ((ic >= 'A' && ic <= 'Z') ||
88                                     (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
89                                      c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
90                                      c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
91                                      c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
92                                         continue;
93
94                                 context.ErrorMessage = "(Invalid verb)";
95                                 return;
96                         }
97                         
98 #if false
99                         //
100                         // According to bug #80504 we should allow any verbs to go
101                         // through.
102                         //
103                         if (Array.IndexOf (methods, method) == -1) {
104                                 context.ErrorMessage = "Invalid request line (verb).";
105                                 return;
106                         }
107 #endif
108
109                         raw_url = parts [1];
110                         if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
111                                 context.ErrorMessage = "Invalid request line (version).";
112                                 return;
113                         }
114
115                         try {
116                                 version = new Version (parts [2].Substring (5));
117                                 if (version.Major < 1)
118                                         throw new Exception ();
119                         } catch {
120                                 context.ErrorMessage = "Invalid request line (version).";
121                                 return;
122                         }
123                 }
124
125                 void CreateQueryString (string query)
126                 {
127                         query_string = new NameValueCollection ();
128                         if (query == null || query.Length == 0)
129                                 return;
130
131                         if (query [0] == '?')
132                                 query = query.Substring (1);
133                         string [] components = query.Split ('&');
134                         foreach (string kv in components) {
135                                 int pos = kv.IndexOf ('=');
136                                 if (pos == -1) {
137                                         query_string.Add (null, HttpUtility.UrlDecode (kv));
138                                 } else {
139                                         string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
140                                         string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
141                                         
142                                         query_string.Add (key, val);
143                                 }
144                         }
145                 }
146
147                 internal void FinishInitialization ()
148                 {
149                         string host = UserHostName;
150                         if (version > HttpVersion.Version10 && (host == null || host == "")) {
151                                 context.ErrorMessage = "Invalid host name";
152                                 return;
153                         }
154
155                         if (host == null || host == "")
156                                 host = UserHostAddress;
157
158                         int colon = host.IndexOf (':');
159                         if (colon >= 0)
160                                 host = host.Substring (0, colon);
161
162                         string base_uri = String.Format ("{0}://{1}:{2}",
163                                                                 (IsSecureConnection) ? "https" : "http",
164                                                                 host,
165                                                                 LocalEndPoint.Port);
166                         try {
167                                 url = new Uri (base_uri + raw_url);
168                         } catch {
169                                 context.ErrorMessage = "Invalid url";
170                                 return;
171                         }
172
173                         CreateQueryString (url.Query);
174
175                         if (method == "GET" || method == "HEAD" || method == "DELETE")
176                                 return;
177
178                         string t_encoding = null;
179                         if (version >= HttpVersion.Version11) {
180                                 t_encoding = Headers ["Transfer-Encoding"];
181                                 // 'identity' is not valid!
182                                 if (t_encoding != null && t_encoding != "chunked") {
183                                         context.Connection.SendError (null, 501);
184                                         return;
185                                 }
186                         }
187
188                         bool is_chunked = (t_encoding == "chunked");
189                         if (!is_chunked && !cl_set) {
190                                 context.Connection.SendError (null, 411);
191                                 return;
192                         }
193
194                         if (is_chunked || content_length > 0) {
195                                 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
196                         }
197
198                         if (Headers ["Expect"] == "100-continue") {
199                                 ResponseStream output = context.Connection.GetResponseStream ();
200                                 output.InternalWrite (_100continue, 0, _100continue.Length);
201                         }
202                 }
203
204                 internal static string Unquote (String str) {
205                         int start = str.IndexOf ('\"');
206                         int end = str.LastIndexOf ('\"');
207                         if (start >= 0 && end >=0)
208                                 str = str.Substring (start + 1, end - 1);
209                         return str.Trim ();
210                 }
211
212                 internal void AddHeader (string header)
213                 {
214                         int colon = header.IndexOf (':');
215                         if (colon == -1 || colon == 0) {
216                                 context.ErrorMessage = "Bad Request";
217                                 return;
218                         }
219
220                         string name = header.Substring (0, colon).Trim ();
221                         string val = header.Substring (colon + 1).Trim ();
222                         string lower = name.ToLower (CultureInfo.InvariantCulture);
223                         headers.SetInternal (name, val);
224                         switch (lower) {
225                                 case "accept-language":
226                                         user_languages = val.Split (','); // yes, only split with a ','
227                                         break;
228                                 case "accept":
229                                         accept_types = val.Split (','); // yes, only split with a ','
230                                         break;
231                                 case "content-length":
232                                         try {
233                                                 //TODO: max. content_length?
234                                                 content_length = Int64.Parse (val.Trim ());
235                                                 if (content_length < 0)
236                                                         context.ErrorMessage = "Invalid Content-Length.";
237                                                 cl_set = true;
238                                         } catch {
239                                                 context.ErrorMessage = "Invalid Content-Length.";
240                                         }
241
242                                         break;
243                                 case "referer":
244                                         try {
245                                                 referrer = new Uri (val);
246                                         } catch {
247                                                 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
248                                         }
249                                         break;
250                                 case "cookie":
251                                         if (cookies == null)
252                                                 cookies = new CookieCollection();
253
254                                         string[] cookieStrings = val.Split(new char[] {',', ';'});
255                                         Cookie current = null;
256                                         int version = 0;
257                                         foreach (string cookieString in cookieStrings) {
258                                                 string str = cookieString.Trim ();
259                                                 if (str.Length == 0)
260                                                         continue;
261                                                 if (str.StartsWith ("$Version")) {
262                                                         version = Int32.Parse (Unquote (str.Substring (str.IndexOf ("=") + 1)));
263                                                 } else if (str.StartsWith ("$Path")) {
264                                                         if (current != null)
265                                                                 current.Path = str.Substring (str.IndexOf ("=") + 1).Trim ();
266                                                 } else if (str.StartsWith ("$Domain")) {
267                                                         if (current != null)
268                                                                 current.Domain = str.Substring (str.IndexOf ("=") + 1).Trim ();
269                                                 } else if (str.StartsWith ("$Port")) {
270                                                         if (current != null)
271                                                                 current.Port = str.Substring (str.IndexOf ("=") + 1).Trim ();
272                                                 } else {
273                                                         if (current != null) {
274                                                                 cookies.Add (current);
275                                                         }
276                                                         current = new Cookie ();
277                                                         int idx = str.IndexOf ("=");
278                                                         if (idx > 0) {
279                                                                 current.Name = str.Substring (0, idx).Trim ();
280                                                                 current.Value =  str.Substring (idx + 1).Trim ();
281                                                         } else {
282                                                                 current.Name = str.Trim ();
283                                                                 current.Value = String.Empty;
284                                                         }
285                                                         current.Version = version;
286                                                 }
287                                         }
288                                         if (current != null) {
289                                                 cookies.Add (current);
290                                         }
291                                         break;
292                         }
293                 }
294
295                 public string [] AcceptTypes {
296                         get { return accept_types; }
297                 }
298
299                 public int ClientCertificateError {
300                         get {
301                                 if (no_get_certificate)
302                                         throw new InvalidOperationException (
303                                                 "Call GetClientCertificate() before calling this method.");
304                                 return client_cert_error;
305                         }
306                 }
307
308                 public Encoding ContentEncoding {
309                         get {
310                                 if (content_encoding == null)
311                                         content_encoding = Encoding.Default;
312                                 return content_encoding;
313                         }
314                 }
315
316                 public long ContentLength64 {
317                         get { return content_length; }
318                 }
319
320                 public string ContentType {
321                         get { return headers ["content-type"]; }
322                 }
323
324                 public CookieCollection Cookies {
325                         get {
326                                 // TODO: check if the collection is read-only
327                                 if (cookies == null)
328                                         cookies = new CookieCollection ();
329                                 return cookies;
330                         }
331                 }
332
333                 public bool HasEntityBody {
334                         get { return !(method == "GET" || method == "HEAD" || content_length <= 0 || is_chunked); }
335                 }
336
337                 public NameValueCollection Headers {
338                         get { return headers; }
339                 }
340
341                 public string HttpMethod {
342                         get { return method; }
343                 }
344
345                 public Stream InputStream {
346                         get { return input_stream; }
347                 }
348
349                 public bool IsAuthenticated {
350                         get { return is_authenticated; }
351                 }
352
353                 public bool IsLocal {
354                         get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
355                 }
356
357                 public bool IsSecureConnection {
358                         get { return context.Connection.IsSecure; } 
359                 }
360
361                 public bool KeepAlive {
362                         get { return false; }
363                 }
364
365                 public IPEndPoint LocalEndPoint {
366                         get { return context.Connection.LocalEndPoint; }
367                 }
368
369                 public Version ProtocolVersion {
370                         get { return version; }
371                 }
372
373                 public NameValueCollection QueryString {
374                         get { return query_string; }
375                 }
376
377                 public string RawUrl {
378                         get { return raw_url; }
379                 }
380
381                 public IPEndPoint RemoteEndPoint {
382                         get { return context.Connection.RemoteEndPoint; }
383                 }
384
385                 public Guid RequestTraceIdentifier {
386                         get { return identifier; }
387                 }
388
389                 public Uri Url {
390                         get { return url; }
391                 }
392
393                 public Uri UrlReferrer {
394                         get { return referrer; }
395                 }
396
397                 public string UserAgent {
398                         get { return headers ["user-agent"]; }
399                 }
400
401                 public string UserHostAddress {
402                         get { return LocalEndPoint.ToString (); }
403                 }
404
405                 public string UserHostName {
406                         get { return headers ["host"]; }
407                 }
408
409                 public string [] UserLanguages {
410                         get { return user_languages; }
411                 }
412
413                 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
414                 {
415                         return null;
416                 }
417 #if SECURITY_DEP
418                 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
419                 {
420                         return null;
421                         // set no_client_certificate once done.
422                 }
423
424                 public X509Certificate2 GetClientCertificate ()
425                 {
426                         // set no_client_certificate once done.
427
428                         // InvalidOp if call in progress.
429                         return null;
430                 }
431 #endif
432         }
433 }
434 #endif
435