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