* Makefile: Add a System.Core.dll reference; embed monodoc.xml as a
[mono.git] / mcs / class / System.Runtime.Remoting / MonoHttp / HttpListenerRequest.cs
1 #define EMBEDDED_IN_1_0
2
3 //
4 // System.Net.HttpListenerRequest
5 //
6 // Author:
7 //      Gonzalo Paniagua Javier (gonzalo@novell.com)
8 //
9 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 #if EMBEDDED_IN_1_0
32
33 using System.Collections;
34 using System.Collections.Specialized;
35 using System.Globalization;
36 using System.IO;
37 using System.Security.Cryptography.X509Certificates;
38 using System.Text;
39 using System; using System.Net; namespace MonoHttp {
40         internal class HttpListenerRequest
41         {
42                 string [] accept_types;
43 //              int client_cert_error;
44 //              bool no_get_certificate;
45                 Encoding content_encoding;
46                 long content_length;
47                 bool cl_set;
48                 CookieCollection cookies;
49                 WebHeaderCollection headers;
50                 string method;
51                 Stream input_stream;
52                 Version version;
53                 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
54                 string raw_url;
55                 Guid identifier;
56                 Uri url;
57                 Uri referrer;
58                 string [] user_languages;
59                 HttpListenerContext context;
60                 bool is_chunked;
61                 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
62                 static readonly string [] no_body_methods = new string [] {
63                         "GET", "HEAD", "DELETE" };
64
65                 internal HttpListenerRequest (HttpListenerContext context)
66                 {
67                         this.context = context;
68                         headers = new WebHeaderCollection ();
69                         input_stream = Stream.Null;
70                         version = HttpVersion.Version10;
71                 }
72
73                 static char [] separators = new char [] { ' ' };
74
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 > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
89                                      c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
90                                      c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
91                                      c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
92                                         continue;
93
94                                 context.ErrorMessage = "(Invalid verb)";
95                                 return;
96                         }
97
98                         raw_url = parts [1];
99                         if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
100                                 context.ErrorMessage = "Invalid request line (version).";
101                                 return;
102                         }
103
104                         try {
105                                 version = new Version (parts [2].Substring (5));
106                                 if (version.Major < 1)
107                                         throw new Exception ();
108                         } catch {
109                                 context.ErrorMessage = "Invalid request line (version).";
110                                 return;
111                         }
112                 }
113
114                 void CreateQueryString (string query)
115                 {
116                         query_string = new NameValueCollection ();
117                         if (query == null || query.Length == 0)
118                                 return;
119
120                         if (query [0] == '?')
121                                 query = query.Substring (1);
122                         string [] components = query.Split ('&');
123                         foreach (string kv in components) {
124                                 int pos = kv.IndexOf ('=');
125                                 if (pos == -1) {
126                                         query_string.Add (null, HttpUtility.UrlDecode (kv));
127                                 } else {
128                                         string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
129                                         string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
130                                         
131                                         query_string.Add (key, val);
132                                 }
133                         }
134                 }
135
136                 internal void FinishInitialization ()
137                 {
138                         string host = UserHostName;
139                         if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
140                                 context.ErrorMessage = "Invalid host name";
141                                 return;
142                         }
143
144                         string path;
145                         Uri raw_uri;
146                         #if NET_2_0
147 if (MonoHttp.Utility.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
148 #else
149 try { raw_uri = new Uri (raw_url); } catch { raw_uri = null; } if (url != raw_uri && (raw_uri.Host == null || raw_uri.Host.Length == 0)) raw_uri = null; if (raw_uri != null)
150 #endif
151
152                                 path = raw_uri.PathAndQuery;
153                         else
154                                 path = raw_url;
155
156                         if ((host == null || host.Length == 0))
157                                 host = UserHostAddress;
158
159                         if (raw_uri != null)
160                                 host = raw_uri.Host;
161         
162                         int colon = host.IndexOf (':');
163                         if (colon >= 0)
164                                 host = host.Substring (0, colon);
165
166                         string base_uri = String.Format ("{0}://{1}:{2}",
167                                                                 (IsSecureConnection) ? "https" : "http",
168                                                                 host,
169                                                                 LocalEndPoint.Port);
170
171                         #if NET_2_0
172 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
173 #else
174 try { url = new Uri (base_uri + path); } catch {}; if (url != null && (url.Host == null || url.Host.Length == 0)) url = null;  if (url == null) {
175 #endif
176
177                                 context.ErrorMessage = "Invalid url: " + base_uri + path;
178                                 return;
179                         }
180
181                         CreateQueryString (url.Query);
182
183                         string t_encoding = null;
184                         if (version >= HttpVersion.Version11) {
185                                 t_encoding = Headers ["Transfer-Encoding"];
186                                 // 'identity' is not valid!
187                                 if (t_encoding != null && t_encoding != "chunked") {
188                                         context.Connection.SendError (null, 501);
189                                         return;
190                                 }
191                         }
192
193                         is_chunked = (t_encoding == "chunked");
194
195                         foreach (string m in no_body_methods)
196                                 if (string.Compare (method, m, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
197                                         return;
198
199                         if (!is_chunked && !cl_set) {
200                                 context.Connection.SendError (null, 411);
201                                 return;
202                         }
203
204                         if (is_chunked || content_length > 0) {
205                                 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
206                         }
207
208                         if (Headers ["Expect"] == "100-continue") {
209                                 ResponseStream output = context.Connection.GetResponseStream ();
210                                 output.InternalWrite (_100continue, 0, _100continue.Length);
211                         }
212                 }
213
214                 internal static string Unquote (String str) {
215                         int start = str.IndexOf ('\"');
216                         int end = str.LastIndexOf ('\"');
217                         if (start >= 0 && end >=0)
218                                 str = str.Substring (start + 1, end - 1);
219                         return str.Trim ();
220                 }
221
222                 internal void AddHeader (string header)
223                 {
224                         int colon = header.IndexOf (':');
225                         if (colon == -1 || colon == 0) {
226                                 context.ErrorMessage = "Bad Request";
227                                 return;
228                         }
229
230                         string name = header.Substring (0, colon).Trim ();
231                         string val = header.Substring (colon + 1).Trim ();
232                         string lower = name.ToLower (CultureInfo.InvariantCulture);
233                         headers.SetInternal (name, val);
234                         switch (lower) {
235                                 case "accept-language":
236                                         user_languages = val.Split (','); // yes, only split with a ','
237                                         break;
238                                 case "accept":
239                                         accept_types = val.Split (','); // yes, only split with a ','
240                                         break;
241                                 case "content-length":
242                                         try {
243                                                 //TODO: max. content_length?
244                                                 content_length = Int64.Parse (val.Trim ());
245                                                 if (content_length < 0)
246                                                         context.ErrorMessage = "Invalid Content-Length.";
247                                                 cl_set = true;
248                                         } catch {
249                                                 context.ErrorMessage = "Invalid Content-Length.";
250                                         }
251
252                                         break;
253                                 case "referer":
254                                         try {
255                                                 referrer = new Uri (val);
256                                         } catch {
257                                                 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
258                                         }
259                                         break;
260                                 case "cookie":
261                                         if (cookies == null)
262                                                 cookies = new CookieCollection();
263
264                                         string[] cookieStrings = val.Split(new char[] {',', ';'});
265                                         Cookie current = null;
266                                         int version = 0;
267                                         foreach (string cookieString in cookieStrings) {
268                                                 string str = cookieString.Trim ();
269                                                 if (str.Length == 0)
270                                                         continue;
271                                                 if (str.StartsWith ("$Version")) {
272                                                         version = Int32.Parse (Unquote (str.Substring (str.IndexOf ("=") + 1)));
273                                                 } else if (str.StartsWith ("$Path")) {
274                                                         if (current != null)
275                                                                 current.Path = str.Substring (str.IndexOf ("=") + 1).Trim ();
276                                                 } else if (str.StartsWith ("$Domain")) {
277                                                         if (current != null)
278                                                                 current.Domain = str.Substring (str.IndexOf ("=") + 1).Trim ();
279                                                 } else if (str.StartsWith ("$Port")) {
280                                                         if (current != null)
281                                                                 current.Port = str.Substring (str.IndexOf ("=") + 1).Trim ();
282                                                 } else {
283                                                         if (current != null) {
284                                                                 cookies.Add (current);
285                                                         }
286                                                         current = new Cookie ();
287                                                         int idx = str.IndexOf ("=");
288                                                         if (idx > 0) {
289                                                                 current.Name = str.Substring (0, idx).Trim ();
290                                                                 current.Value =  str.Substring (idx + 1).Trim ();
291                                                         } else {
292                                                                 current.Name = str.Trim ();
293                                                                 current.Value = String.Empty;
294                                                         }
295                                                         current.Version = version;
296                                                 }
297                                         }
298                                         if (current != null) {
299                                                 cookies.Add (current);
300                                         }
301                                         break;
302                         }
303                 }
304
305                 public string [] AcceptTypes {
306                         get { return accept_types; }
307                 }
308
309                 [MonoTODO ("Always returns 0")]
310                 public int ClientCertificateError {
311                         get {
312 /*                              
313                                 if (no_get_certificate)
314                                         throw new InvalidOperationException (
315                                                 "Call GetClientCertificate() before calling this method.");
316                                 return client_cert_error;
317 */
318                                 return 0;
319                         }
320                 }
321
322                 public Encoding ContentEncoding {
323                         get {
324                                 if (content_encoding == null)
325                                         content_encoding = Encoding.Default;
326                                 return content_encoding;
327                         }
328                 }
329
330                 public long ContentLength64 {
331                         get { return content_length; }
332                 }
333
334                 public string ContentType {
335                         get { return headers ["content-type"]; }
336                 }
337
338                 public CookieCollection Cookies {
339                         get {
340                                 // TODO: check if the collection is read-only
341                                 if (cookies == null)
342                                         cookies = new CookieCollection ();
343                                 return cookies;
344                         }
345                 }
346
347                 public bool HasEntityBody {
348                         get { return (content_length > 0 || is_chunked); }
349                 }
350
351                 public NameValueCollection Headers {
352                         get { return headers; }
353                 }
354
355                 public string HttpMethod {
356                         get { return method; }
357                 }
358
359                 public Stream InputStream {
360                         get { return input_stream; }
361                 }
362
363                 [MonoTODO ("Always returns false")]
364                 public bool IsAuthenticated {
365                         get { return false; }
366                 }
367
368                 public bool IsLocal {
369                         get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
370                 }
371
372                 public bool IsSecureConnection {
373                         get { return context.Connection.IsSecure; } 
374                 }
375
376                 public bool KeepAlive {
377                         get { return false; }
378                 }
379
380                 public IPEndPoint LocalEndPoint {
381                         get { return context.Connection.LocalEndPoint; }
382                 }
383
384                 public Version ProtocolVersion {
385                         get { return version; }
386                 }
387
388                 public NameValueCollection QueryString {
389                         get { return query_string; }
390                 }
391
392                 public string RawUrl {
393                         get { return raw_url; }
394                 }
395
396                 public IPEndPoint RemoteEndPoint {
397                         get { return context.Connection.RemoteEndPoint; }
398                 }
399
400                 public Guid RequestTraceIdentifier {
401                         get { return identifier; }
402                 }
403
404                 public Uri Url {
405                         get { return url; }
406                 }
407
408                 public Uri UrlReferrer {
409                         get { return referrer; }
410                 }
411
412                 public string UserAgent {
413                         get { return headers ["user-agent"]; }
414                 }
415
416                 public string UserHostAddress {
417                         get { return LocalEndPoint.ToString (); }
418                 }
419
420                 public string UserHostName {
421                         get { return headers ["host"]; }
422                 }
423
424                 public string [] UserLanguages {
425                         get { return user_languages; }
426                 }
427
428                 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
429                 {
430                         return null;
431                 }
432 #if SECURITY_DEP
433                 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
434                 {
435                         return null;
436                         // set no_client_certificate once done.
437                 }
438
439                 public X509Certificate2 GetClientCertificate ()
440                 {
441                         // set no_client_certificate once done.
442
443                         // InvalidOp if call in progress.
444                         return null;
445                 }
446 #endif
447         }
448 }
449 #endif
450