Moved ProviderCollectionTest.cs from System assembly to System.Configuration.
[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                 Guid identifier;
54                 Uri url;
55                 Uri referrer;
56                 string [] user_languages;
57                 HttpListenerContext context;
58                 bool is_chunked;
59                 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
60                 static readonly string [] no_body_methods = new string [] {
61                         "GET", "HEAD", "DELETE" };
62
63                 internal HttpListenerRequest (HttpListenerContext context)
64                 {
65                         this.context = context;
66                         headers = new WebHeaderCollection ();
67                         input_stream = Stream.Null;
68                 }
69
70                 static char [] separators = new char [] { ' ' };
71
72                 internal void SetRequestLine (string req)
73                 {
74                         string [] parts = req.Split (separators, 3);
75                         if (parts.Length != 3) {
76                                 context.ErrorMessage = "Invalid request line (parts).";
77                                 return;
78                         }
79
80                         method = parts [0];
81                         foreach (char c in method){
82                                 int ic = (int) c;
83
84                                 if ((ic >= 'A' && ic <= 'Z') ||
85                                     (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
86                                      c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
87                                      c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
88                                      c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
89                                         continue;
90
91                                 context.ErrorMessage = "(Invalid verb)";
92                                 return;
93                         }
94
95                         raw_url = parts [1];
96                         if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
97                                 context.ErrorMessage = "Invalid request line (version).";
98                                 return;
99                         }
100
101                         try {
102                                 version = new Version (parts [2].Substring (5));
103                                 if (version.Major < 1)
104                                         throw new Exception ();
105                         } catch {
106                                 context.ErrorMessage = "Invalid request line (version).";
107                                 return;
108                         }
109                 }
110
111                 void CreateQueryString (string query)
112                 {
113                         query_string = new NameValueCollection ();
114                         if (query == null || query.Length == 0)
115                                 return;
116
117                         if (query [0] == '?')
118                                 query = query.Substring (1);
119                         string [] components = query.Split ('&');
120                         foreach (string kv in components) {
121                                 int pos = kv.IndexOf ('=');
122                                 if (pos == -1) {
123                                         query_string.Add (null, HttpUtility.UrlDecode (kv));
124                                 } else {
125                                         string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
126                                         string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
127                                         
128                                         query_string.Add (key, val);
129                                 }
130                         }
131                 }
132
133                 internal void FinishInitialization ()
134                 {
135                         string host = UserHostName;
136                         if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
137                                 context.ErrorMessage = "Invalid host name";
138                                 return;
139                         }
140
141                         string path;
142                         Uri raw_uri;
143                         if (Uri.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
144                                 path = raw_uri.PathAndQuery;
145                         else
146                                 path = raw_url;
147
148                         if ((host == null || host.Length == 0))
149                                 host = UserHostAddress;
150
151                         if (raw_uri != null)
152                                 host = raw_uri.Host;
153         
154                         int colon = host.IndexOf (':');
155                         if (colon >= 0)
156                                 host = host.Substring (0, colon);
157
158                         string base_uri = String.Format ("{0}://{1}:{2}",
159                                                                 (IsSecureConnection) ? "https" : "http",
160                                                                 host,
161                                                                 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                         string t_encoding = null;
171                         if (version >= HttpVersion.Version11) {
172                                 t_encoding = Headers ["Transfer-Encoding"];
173                                 // 'identity' is not valid!
174                                 if (t_encoding != null && t_encoding != "chunked") {
175                                         context.Connection.SendError (null, 501);
176                                         return;
177                                 }
178                         }
179
180                         is_chunked = (t_encoding == "chunked");
181
182                         foreach (string m in no_body_methods)
183                                 if (string.Compare (method, m, StringComparison.InvariantCultureIgnoreCase) == 0)
184                                         return;
185
186                         if (!is_chunked && !cl_set) {
187                                 context.Connection.SendError (null, 411);
188                                 return;
189                         }
190
191                         if (is_chunked || content_length > 0) {
192                                 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
193                         }
194
195                         if (Headers ["Expect"] == "100-continue") {
196                                 ResponseStream output = context.Connection.GetResponseStream ();
197                                 output.InternalWrite (_100continue, 0, _100continue.Length);
198                         }
199                 }
200
201                 internal static string Unquote (String str) {
202                         int start = str.IndexOf ('\"');
203                         int end = str.LastIndexOf ('\"');
204                         if (start >= 0 && end >=0)
205                                 str = str.Substring (start + 1, end - 1);
206                         return str.Trim ();
207                 }
208
209                 internal void AddHeader (string header)
210                 {
211                         int colon = header.IndexOf (':');
212                         if (colon == -1 || colon == 0) {
213                                 context.ErrorMessage = "Bad Request";
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                 public string [] AcceptTypes {
293                         get { return accept_types; }
294                 }
295
296                 [MonoTODO ("Always returns 0")]
297                 public int ClientCertificateError {
298                         get {
299 /*                              
300                                 if (no_get_certificate)
301                                         throw new InvalidOperationException (
302                                                 "Call GetClientCertificate() before calling this method.");
303                                 return client_cert_error;
304 */
305                                 return 0;
306                         }
307                 }
308
309                 public Encoding ContentEncoding {
310                         get {
311                                 if (content_encoding == null)
312                                         content_encoding = Encoding.Default;
313                                 return content_encoding;
314                         }
315                 }
316
317                 public long ContentLength64 {
318                         get { return content_length; }
319                 }
320
321                 public string ContentType {
322                         get { return headers ["content-type"]; }
323                 }
324
325                 public CookieCollection Cookies {
326                         get {
327                                 // TODO: check if the collection is read-only
328                                 if (cookies == null)
329                                         cookies = new CookieCollection ();
330                                 return cookies;
331                         }
332                 }
333
334                 public bool HasEntityBody {
335                         get { return (content_length > 0 || is_chunked); }
336                 }
337
338                 public NameValueCollection Headers {
339                         get { return headers; }
340                 }
341
342                 public string HttpMethod {
343                         get { return method; }
344                 }
345
346                 public Stream InputStream {
347                         get { return input_stream; }
348                 }
349
350                 [MonoTODO ("Always returns false")]
351                 public bool IsAuthenticated {
352                         get { return false; }
353                 }
354
355                 public bool IsLocal {
356                         get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
357                 }
358
359                 public bool IsSecureConnection {
360                         get { return context.Connection.IsSecure; } 
361                 }
362
363                 public bool KeepAlive {
364                         get { return false; }
365                 }
366
367                 public IPEndPoint LocalEndPoint {
368                         get { return context.Connection.LocalEndPoint; }
369                 }
370
371                 public Version ProtocolVersion {
372                         get { return version; }
373                 }
374
375                 public NameValueCollection QueryString {
376                         get { return query_string; }
377                 }
378
379                 public string RawUrl {
380                         get { return raw_url; }
381                 }
382
383                 public IPEndPoint RemoteEndPoint {
384                         get { return context.Connection.RemoteEndPoint; }
385                 }
386
387                 public Guid RequestTraceIdentifier {
388                         get { return identifier; }
389                 }
390
391                 public Uri Url {
392                         get { return url; }
393                 }
394
395                 public Uri UrlReferrer {
396                         get { return referrer; }
397                 }
398
399                 public string UserAgent {
400                         get { return headers ["user-agent"]; }
401                 }
402
403                 public string UserHostAddress {
404                         get { return LocalEndPoint.ToString (); }
405                 }
406
407                 public string UserHostName {
408                         get { return headers ["host"]; }
409                 }
410
411                 public string [] UserLanguages {
412                         get { return user_languages; }
413                 }
414
415                 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
416                 {
417                         return null;
418                 }
419 #if SECURITY_DEP
420                 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
421                 {
422                         return null;
423                         // set no_client_certificate once done.
424                 }
425
426                 public X509Certificate2 GetClientCertificate ()
427                 {
428                         // set no_client_certificate once done.
429
430                         // InvalidOp if call in progress.
431                         return null;
432                 }
433 #endif
434         }
435 }
436 #endif
437