* HttpListenerRequestTest.cs: Added test for HasEntityBody.
[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                 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].ToUpperInvariant ();
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                         if (host == null || host.Length == 0)
141                                 host = UserHostAddress;
142
143                         int colon = host.IndexOf (':');
144                         if (colon >= 0)
145                                 host = host.Substring (0, colon);
146
147                         string base_uri = String.Format ("{0}://{1}:{2}",
148                                                                 (IsSecureConnection) ? "https" : "http",
149                                                                 host,
150                                                                 LocalEndPoint.Port);
151                         try {
152                                 url = new Uri (base_uri + raw_url);
153                         } catch {
154                                 context.ErrorMessage = "Invalid url";
155                                 return;
156                         }
157
158                         CreateQueryString (url.Query);
159
160                         string t_encoding = null;
161                         if (version >= HttpVersion.Version11) {
162                                 t_encoding = Headers ["Transfer-Encoding"];
163                                 // 'identity' is not valid!
164                                 if (t_encoding != null && t_encoding != "chunked") {
165                                         context.Connection.SendError (null, 501);
166                                         return;
167                                 }
168                         }
169
170                         is_chunked = (t_encoding == "chunked");
171
172                         if (method == "GET" || method == "HEAD" || method == "DELETE")
173                                 return;
174
175                         if (!is_chunked && !cl_set) {
176                                 context.Connection.SendError (null, 411);
177                                 return;
178                         }
179
180                         if (is_chunked || content_length > 0) {
181                                 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
182                         }
183
184                         if (Headers ["Expect"] == "100-continue") {
185                                 ResponseStream output = context.Connection.GetResponseStream ();
186                                 output.InternalWrite (_100continue, 0, _100continue.Length);
187                         }
188                 }
189
190                 internal static string Unquote (String str) {
191                         int start = str.IndexOf ('\"');
192                         int end = str.LastIndexOf ('\"');
193                         if (start >= 0 && end >=0)
194                                 str = str.Substring (start + 1, end - 1);
195                         return str.Trim ();
196                 }
197
198                 internal void AddHeader (string header)
199                 {
200                         int colon = header.IndexOf (':');
201                         if (colon == -1 || colon == 0) {
202                                 context.ErrorMessage = "Bad Request";
203                                 return;
204                         }
205
206                         string name = header.Substring (0, colon).Trim ();
207                         string val = header.Substring (colon + 1).Trim ();
208                         string lower = name.ToLower (CultureInfo.InvariantCulture);
209                         headers.SetInternal (name, val);
210                         switch (lower) {
211                                 case "accept-language":
212                                         user_languages = val.Split (','); // yes, only split with a ','
213                                         break;
214                                 case "accept":
215                                         accept_types = val.Split (','); // yes, only split with a ','
216                                         break;
217                                 case "content-length":
218                                         try {
219                                                 //TODO: max. content_length?
220                                                 content_length = Int64.Parse (val.Trim ());
221                                                 if (content_length < 0)
222                                                         context.ErrorMessage = "Invalid Content-Length.";
223                                                 cl_set = true;
224                                         } catch {
225                                                 context.ErrorMessage = "Invalid Content-Length.";
226                                         }
227
228                                         break;
229                                 case "referer":
230                                         try {
231                                                 referrer = new Uri (val);
232                                         } catch {
233                                                 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
234                                         }
235                                         break;
236                                 case "cookie":
237                                         if (cookies == null)
238                                                 cookies = new CookieCollection();
239
240                                         string[] cookieStrings = val.Split(new char[] {',', ';'});
241                                         Cookie current = null;
242                                         int version = 0;
243                                         foreach (string cookieString in cookieStrings) {
244                                                 string str = cookieString.Trim ();
245                                                 if (str.Length == 0)
246                                                         continue;
247                                                 if (str.StartsWith ("$Version")) {
248                                                         version = Int32.Parse (Unquote (str.Substring (str.IndexOf ("=") + 1)));
249                                                 } else if (str.StartsWith ("$Path")) {
250                                                         if (current != null)
251                                                                 current.Path = str.Substring (str.IndexOf ("=") + 1).Trim ();
252                                                 } else if (str.StartsWith ("$Domain")) {
253                                                         if (current != null)
254                                                                 current.Domain = str.Substring (str.IndexOf ("=") + 1).Trim ();
255                                                 } else if (str.StartsWith ("$Port")) {
256                                                         if (current != null)
257                                                                 current.Port = str.Substring (str.IndexOf ("=") + 1).Trim ();
258                                                 } else {
259                                                         if (current != null) {
260                                                                 cookies.Add (current);
261                                                         }
262                                                         current = new Cookie ();
263                                                         int idx = str.IndexOf ("=");
264                                                         if (idx > 0) {
265                                                                 current.Name = str.Substring (0, idx).Trim ();
266                                                                 current.Value =  str.Substring (idx + 1).Trim ();
267                                                         } else {
268                                                                 current.Name = str.Trim ();
269                                                                 current.Value = String.Empty;
270                                                         }
271                                                         current.Version = version;
272                                                 }
273                                         }
274                                         if (current != null) {
275                                                 cookies.Add (current);
276                                         }
277                                         break;
278                         }
279                 }
280
281                 public string [] AcceptTypes {
282                         get { return accept_types; }
283                 }
284
285                 public int ClientCertificateError {
286                         get {
287                                 if (no_get_certificate)
288                                         throw new InvalidOperationException (
289                                                 "Call GetClientCertificate() before calling this method.");
290                                 return client_cert_error;
291                         }
292                 }
293
294                 public Encoding ContentEncoding {
295                         get {
296                                 if (content_encoding == null)
297                                         content_encoding = Encoding.Default;
298                                 return content_encoding;
299                         }
300                 }
301
302                 public long ContentLength64 {
303                         get { return content_length; }
304                 }
305
306                 public string ContentType {
307                         get { return headers ["content-type"]; }
308                 }
309
310                 public CookieCollection Cookies {
311                         get {
312                                 // TODO: check if the collection is read-only
313                                 if (cookies == null)
314                                         cookies = new CookieCollection ();
315                                 return cookies;
316                         }
317                 }
318
319                 public bool HasEntityBody {
320                         get { return (content_length > 0 || is_chunked); }
321                 }
322
323                 public NameValueCollection Headers {
324                         get { return headers; }
325                 }
326
327                 public string HttpMethod {
328                         get { return method; }
329                 }
330
331                 public Stream InputStream {
332                         get { return input_stream; }
333                 }
334
335                 public bool IsAuthenticated {
336                         get { return is_authenticated; }
337                 }
338
339                 public bool IsLocal {
340                         get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
341                 }
342
343                 public bool IsSecureConnection {
344                         get { return context.Connection.IsSecure; } 
345                 }
346
347                 public bool KeepAlive {
348                         get { return false; }
349                 }
350
351                 public IPEndPoint LocalEndPoint {
352                         get { return context.Connection.LocalEndPoint; }
353                 }
354
355                 public Version ProtocolVersion {
356                         get { return version; }
357                 }
358
359                 public NameValueCollection QueryString {
360                         get { return query_string; }
361                 }
362
363                 public string RawUrl {
364                         get { return raw_url; }
365                 }
366
367                 public IPEndPoint RemoteEndPoint {
368                         get { return context.Connection.RemoteEndPoint; }
369                 }
370
371                 public Guid RequestTraceIdentifier {
372                         get { return identifier; }
373                 }
374
375                 public Uri Url {
376                         get { return url; }
377                 }
378
379                 public Uri UrlReferrer {
380                         get { return referrer; }
381                 }
382
383                 public string UserAgent {
384                         get { return headers ["user-agent"]; }
385                 }
386
387                 public string UserHostAddress {
388                         get { return LocalEndPoint.ToString (); }
389                 }
390
391                 public string UserHostName {
392                         get { return headers ["host"]; }
393                 }
394
395                 public string [] UserLanguages {
396                         get { return user_languages; }
397                 }
398
399                 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
400                 {
401                         return null;
402                 }
403 #if SECURITY_DEP
404                 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
405                 {
406                         return null;
407                         // set no_client_certificate once done.
408                 }
409
410                 public X509Certificate2 GetClientCertificate ()
411                 {
412                         // set no_client_certificate once done.
413
414                         // InvalidOp if call in progress.
415                         return null;
416                 }
417 #endif
418         }
419 }
420 #endif
421