New test.
[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 #if NET_2_0
29 using System.Collections;
30 using System.Collections.Specialized;
31 using System.Globalization;
32 using System.IO;
33 using System.Security.Cryptography.X509Certificates;
34 using System.Text;
35 namespace System.Net {
36         public sealed class HttpListenerRequest
37         {
38                 string [] accept_types;
39                 int client_cert_error;
40                 Encoding content_encoding;
41                 long content_length;
42                 bool cl_set;
43                 CookieCollection cookies;
44                 WebHeaderCollection headers;
45                 string method;
46                 Stream input_stream;
47                 bool is_authenticated;
48                 Version version;
49                 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
50                 string raw_url;
51                 Guid identifier;
52                 Uri url;
53                 Uri referrer;
54                 string [] user_languages;
55                 bool no_get_certificate;
56                 HttpListenerContext context;
57                 bool is_chunked;
58                 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
59
60                 internal HttpListenerRequest (HttpListenerContext context)
61                 {
62                         this.context = context;
63                         headers = new WebHeaderCollection ();
64                         input_stream = Stream.Null;
65                 }
66
67                 static char [] separators = new char [] { ' ' };
68                 // From WebRequestMethods.Http
69                 static readonly string [] methods = new string [] { "GET", "POST", "HEAD",
70                                                                 "PUT", "CONNECT", "MKCOL" };
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                         if (Array.IndexOf (methods, method) == -1) {
81                                 context.ErrorMessage = "Invalid request line (verb).";
82                                 return;
83                         }
84
85                         raw_url = parts [1];
86                         if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
87                                 context.ErrorMessage = "Invalid request line (version).";
88                                 return;
89                         }
90
91                         try {
92                                 version = new Version (parts [2].Substring (5));
93                                 if (version.Major < 1)
94                                         throw new Exception ();
95                         } catch {
96                                 context.ErrorMessage = "Invalid request line (version).";
97                                 return;
98                         }
99                 }
100
101                 void CreateQueryString (string query)
102                 {
103                         query_string = new NameValueCollection ();
104                         if (query == null || query.Length == 0)
105                                 return;
106
107                         string [] components = query.Split ('&');
108                         foreach (string kv in components) {
109                                 int pos = kv.IndexOf ('=');
110                                 if (pos == -1) {
111                                         query_string.Add (null, HttpUtility.UrlDecode (kv));
112                                 } else {
113                                         string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
114                                         string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
115                                         
116                                         query_string.Add (key, val);
117                                 }
118                         }
119                 }
120
121                 internal void FinishInitialization ()
122                 {
123                         string host = UserHostName;
124                         if (version > HttpVersion.Version10 && (host == null || host == "")) {
125                                 context.ErrorMessage = "Invalid host name";
126                                 return;
127                         }
128
129                         if (host == null || host == "")
130                                 host = UserHostAddress;
131
132                         int colon = host.IndexOf (':');
133                         if (colon >= 0)
134                                 host = host.Substring (0, colon);
135
136                         string base_uri = String.Format ("{0}://{1}:{2}",
137                                                                 (IsSecureConnection) ? "https" : "http",
138                                                                 host,
139                                                                 LocalEndPoint.Port);
140                         try {
141                                 url = new Uri (base_uri + raw_url);
142                         } catch {
143                                 context.ErrorMessage = "Invalid url";
144                                 return;
145                         }
146
147                         CreateQueryString (url.Query);
148
149                         if (method == "GET" || method == "HEAD")
150                                 return;
151
152                         string t_encoding = null;
153                         if (version >= HttpVersion.Version11) {
154                                 t_encoding = Headers ["Transfer-Encoding"];
155                                 // 'identity' is not valid!
156                                 if (t_encoding != null && t_encoding != "chunked") {
157                                         context.Connection.SendError (null, 501);
158                                         return;
159                                 }
160                         }
161
162                         bool is_chunked = (t_encoding == "chunked");
163                         if (!is_chunked && !cl_set) {
164                                 context.Connection.SendError (null, 411);
165                                 return;
166                         }
167
168                         if (is_chunked || content_length > 0) {
169                                 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
170                         }
171
172                         if (Headers ["Expect"] == "100-continue") {
173                                 ResponseStream output = context.Connection.GetResponseStream ();
174                                 output.InternalWrite (_100continue, 0, _100continue.Length);
175                         }
176                 }
177
178                 internal void AddHeader (string header)
179                 {
180                         int colon = header.IndexOf (':');
181                         if (colon == -1 || colon == 0) {
182                                 context.ErrorMessage = "Bad Request";
183                                 return;
184                         }
185
186                         string name = header.Substring (0, colon).Trim ();
187                         string val = header.Substring (colon + 1).Trim ();
188                         string lower = name.ToLower (CultureInfo.InvariantCulture);
189                         headers.SetInternal (name, val);
190                         switch (lower) {
191                                 case "accept-language":
192                                         user_languages = val.Split (','); // yes, only split with a ','
193                                         break;
194                                 case "accept-types":
195                                         accept_types = val.Split (','); // yes, only split with a ','
196                                         break;
197                                 case "content-length":
198                                         try {
199                                                 //TODO: max. content_length?
200                                                 content_length = Int64.Parse (val.Trim ());
201                                                 if (content_length < 0)
202                                                         context.ErrorMessage = "Invalid Content-Length.";
203                                                 cl_set = true;
204                                         } catch {
205                                                 context.ErrorMessage = "Invalid Content-Length.";
206                                         }
207
208                                         break;
209                                 case "referer":
210                                         try {
211                                                 referrer = new Uri (val);
212                                         } catch {
213                                                 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
214                                         }
215                                         break;
216                                 //TODO: cookie headers
217                         }
218                 }
219
220                 public string [] AcceptTypes {
221                         get { return accept_types; }
222                 }
223
224                 public int ClientCertificateError {
225                         get {
226                                 if (no_get_certificate)
227                                         throw new InvalidOperationException (
228                                                 "Call GetClientCertificate() before calling this method.");
229                                 return client_cert_error;
230                         }
231                 }
232
233                 public Encoding ContentEncoding {
234                         get {
235                                 if (content_encoding == null)
236                                         content_encoding = Encoding.Default;
237                                 return content_encoding;
238                         }
239                 }
240
241                 public long ContentLength64 {
242                         get { return content_length; }
243                 }
244
245                 public string ContentType {
246                         get { return headers ["content-type"]; }
247                 }
248
249                 public CookieCollection Cookies {
250                         get {
251                                 // TODO: check if the collection is read-only
252                                 if (cookies == null)
253                                         cookies = new CookieCollection ();
254                                 return cookies;
255                         }
256                 }
257
258                 public bool HasEntityBody {
259                         get { return (method == "GET" || method == "HEAD" || content_length <= 0 || is_chunked); }
260                 }
261
262                 public NameValueCollection Headers {
263                         get { return headers; }
264                 }
265
266                 public string HttpMethod {
267                         get { return method; }
268                 }
269
270                 public Stream InputStream {
271                         get { return input_stream; }
272                 }
273
274                 public bool IsAuthenticated {
275                         get { return is_authenticated; }
276                 }
277
278                 public bool IsLocal {
279                         get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
280                 }
281
282                 public bool IsSecureConnection {
283                         get { return context.Connection.IsSecure; } 
284                 }
285
286                 public bool KeepAlive {
287                         get { return false; }
288                 }
289
290                 public IPEndPoint LocalEndPoint {
291                         get { return context.Connection.LocalEndPoint; }
292                 }
293
294                 public Version ProtocolVersion {
295                         get { return version; }
296                 }
297
298                 public NameValueCollection QueryString {
299                         get { return query_string; }
300                 }
301
302                 public string RawUrl {
303                         get { return raw_url; }
304                 }
305
306                 public IPEndPoint RemoteEndPoint {
307                         get { return context.Connection.RemoteEndPoint; }
308                 }
309
310                 public Guid RequestTraceIdentifier {
311                         get { return identifier; }
312                 }
313
314                 public Uri Url {
315                         get { return url; }
316                 }
317
318                 public Uri UrlReferrer {
319                         get { return referrer; }
320                 }
321
322                 public string UserAgent {
323                         get { return headers ["user-agent"]; }
324                 }
325
326                 public string UserHostAddress {
327                         get { return LocalEndPoint.ToString (); }
328                 }
329
330                 public string UserHostName {
331                         get { return headers ["host"]; }
332                 }
333
334                 public string [] UserLanguages {
335                         get { return user_languages; }
336                 }
337
338                 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
339                 {
340                         return null;
341                 }
342 #if SECURITY_DEP
343                 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
344                 {
345                         return null;
346                         // set no_client_certificate once done.
347                 }
348
349                 public X509Certificate2 GetClientCertificate ()
350                 {
351                         // set no_client_certificate once done.
352
353                         // InvalidOp if call in progress.
354                         return null;
355                 }
356 #endif
357         }
358 }
359 #endif
360