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