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