svn path=/trunk/mcs/; revision=113894
[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                 }
71
72                 static char [] separators = new char [] { ' ' };
73
74                 internal void SetRequestLine (string req)
75                 {
76                         string [] parts = req.Split (separators, 3);
77                         if (parts.Length != 3) {
78                                 context.ErrorMessage = "Invalid request line (parts).";
79                                 return;
80                         }
81
82                         method = parts [0];
83                         foreach (char c in method){
84                                 int ic = (int) c;
85
86                                 if ((ic >= 'A' && ic <= 'Z') ||
87                                     (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
88                                      c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
89                                      c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
90                                      c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
91                                         continue;
92
93                                 context.ErrorMessage = "(Invalid verb)";
94                                 return;
95                         }
96
97                         raw_url = parts [1];
98                         if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
99                                 context.ErrorMessage = "Invalid request line (version).";
100                                 return;
101                         }
102
103                         try {
104                                 version = new Version (parts [2].Substring (5));
105                                 if (version.Major < 1)
106                                         throw new Exception ();
107                         } catch {
108                                 context.ErrorMessage = "Invalid request line (version).";
109                                 return;
110                         }
111                 }
112
113                 void CreateQueryString (string query)
114                 {
115                         query_string = new NameValueCollection ();
116                         if (query == null || query.Length == 0)
117                                 return;
118
119                         if (query [0] == '?')
120                                 query = query.Substring (1);
121                         string [] components = query.Split ('&');
122                         foreach (string kv in components) {
123                                 int pos = kv.IndexOf ('=');
124                                 if (pos == -1) {
125                                         query_string.Add (null, HttpUtility.UrlDecode (kv));
126                                 } else {
127                                         string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
128                                         string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
129                                         
130                                         query_string.Add (key, val);
131                                 }
132                         }
133                 }
134
135                 internal void FinishInitialization ()
136                 {
137                         string host = UserHostName;
138                         if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
139                                 context.ErrorMessage = "Invalid host name";
140                                 return;
141                         }
142
143                         string path;
144                         Uri raw_uri;
145                         #if NET_2_0
146 if (MonoHttp.Utility.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
147 #else
148 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)
149 #endif
150
151                                 path = raw_uri.PathAndQuery;
152                         else
153                                 path = raw_url;
154
155                         if ((host == null || host.Length == 0))
156                                 host = UserHostAddress;
157
158                         if (raw_uri != null)
159                                 host = raw_uri.Host;
160         
161                         int colon = host.IndexOf (':');
162                         if (colon >= 0)
163                                 host = host.Substring (0, colon);
164
165                         string base_uri = String.Format ("{0}://{1}:{2}",
166                                                                 (IsSecureConnection) ? "https" : "http",
167                                                                 host,
168                                                                 LocalEndPoint.Port);
169
170                         #if NET_2_0
171 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
172 #else
173 try { url = new Uri (base_uri + path); } catch {}; if (url != null && (url.Host == null || url.Host.Length == 0)) url = null;  if (url == null) {
174 #endif
175
176                                 context.ErrorMessage = "Invalid url: " + base_uri + path;
177                                 return;
178                         }
179
180                         CreateQueryString (url.Query);
181
182                         string t_encoding = null;
183                         if (version >= HttpVersion.Version11) {
184                                 t_encoding = Headers ["Transfer-Encoding"];
185                                 // 'identity' is not valid!
186                                 if (t_encoding != null && t_encoding != "chunked") {
187                                         context.Connection.SendError (null, 501);
188                                         return;
189                                 }
190                         }
191
192                         is_chunked = (t_encoding == "chunked");
193
194                         foreach (string m in no_body_methods)
195                                 if (string.Compare (method, m, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
196                                         return;
197
198                         if (!is_chunked && !cl_set) {
199                                 context.Connection.SendError (null, 411);
200                                 return;
201                         }
202
203                         if (is_chunked || content_length > 0) {
204                                 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
205                         }
206
207                         if (Headers ["Expect"] == "100-continue") {
208                                 ResponseStream output = context.Connection.GetResponseStream ();
209                                 output.InternalWrite (_100continue, 0, _100continue.Length);
210                         }
211                 }
212
213                 internal static string Unquote (String str) {
214                         int start = str.IndexOf ('\"');
215                         int end = str.LastIndexOf ('\"');
216                         if (start >= 0 && end >=0)
217                                 str = str.Substring (start + 1, end - 1);
218                         return str.Trim ();
219                 }
220
221                 internal void AddHeader (string header)
222                 {
223                         int colon = header.IndexOf (':');
224                         if (colon == -1 || colon == 0) {
225                                 context.ErrorMessage = "Bad Request";
226                                 return;
227                         }
228
229                         string name = header.Substring (0, colon).Trim ();
230                         string val = header.Substring (colon + 1).Trim ();
231                         string lower = name.ToLower (CultureInfo.InvariantCulture);
232                         headers.SetInternal (name, val);
233                         switch (lower) {
234                                 case "accept-language":
235                                         user_languages = val.Split (','); // yes, only split with a ','
236                                         break;
237                                 case "accept":
238                                         accept_types = val.Split (','); // yes, only split with a ','
239                                         break;
240                                 case "content-length":
241                                         try {
242                                                 //TODO: max. content_length?
243                                                 content_length = Int64.Parse (val.Trim ());
244                                                 if (content_length < 0)
245                                                         context.ErrorMessage = "Invalid Content-Length.";
246                                                 cl_set = true;
247                                         } catch {
248                                                 context.ErrorMessage = "Invalid Content-Length.";
249                                         }
250
251                                         break;
252                                 case "referer":
253                                         try {
254                                                 referrer = new Uri (val);
255                                         } catch {
256                                                 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
257                                         }
258                                         break;
259                                 case "cookie":
260                                         if (cookies == null)
261                                                 cookies = new CookieCollection();
262
263                                         string[] cookieStrings = val.Split(new char[] {',', ';'});
264                                         Cookie current = null;
265                                         int version = 0;
266                                         foreach (string cookieString in cookieStrings) {
267                                                 string str = cookieString.Trim ();
268                                                 if (str.Length == 0)
269                                                         continue;
270                                                 if (str.StartsWith ("$Version")) {
271                                                         version = Int32.Parse (Unquote (str.Substring (str.IndexOf ("=") + 1)));
272                                                 } else if (str.StartsWith ("$Path")) {
273                                                         if (current != null)
274                                                                 current.Path = str.Substring (str.IndexOf ("=") + 1).Trim ();
275                                                 } else if (str.StartsWith ("$Domain")) {
276                                                         if (current != null)
277                                                                 current.Domain = str.Substring (str.IndexOf ("=") + 1).Trim ();
278                                                 } else if (str.StartsWith ("$Port")) {
279                                                         if (current != null)
280                                                                 current.Port = str.Substring (str.IndexOf ("=") + 1).Trim ();
281                                                 } else {
282                                                         if (current != null) {
283                                                                 cookies.Add (current);
284                                                         }
285                                                         current = new Cookie ();
286                                                         int idx = str.IndexOf ("=");
287                                                         if (idx > 0) {
288                                                                 current.Name = str.Substring (0, idx).Trim ();
289                                                                 current.Value =  str.Substring (idx + 1).Trim ();
290                                                         } else {
291                                                                 current.Name = str.Trim ();
292                                                                 current.Value = String.Empty;
293                                                         }
294                                                         current.Version = version;
295                                                 }
296                                         }
297                                         if (current != null) {
298                                                 cookies.Add (current);
299                                         }
300                                         break;
301                         }
302                 }
303
304                 public string [] AcceptTypes {
305                         get { return accept_types; }
306                 }
307
308                 [MonoTODO ("Always returns 0")]
309                 public int ClientCertificateError {
310                         get {
311 /*                              
312                                 if (no_get_certificate)
313                                         throw new InvalidOperationException (
314                                                 "Call GetClientCertificate() before calling this method.");
315                                 return client_cert_error;
316 */
317                                 return 0;
318                         }
319                 }
320
321                 public Encoding ContentEncoding {
322                         get {
323                                 if (content_encoding == null)
324                                         content_encoding = Encoding.Default;
325                                 return content_encoding;
326                         }
327                 }
328
329                 public long ContentLength64 {
330                         get { return content_length; }
331                 }
332
333                 public string ContentType {
334                         get { return headers ["content-type"]; }
335                 }
336
337                 public CookieCollection Cookies {
338                         get {
339                                 // TODO: check if the collection is read-only
340                                 if (cookies == null)
341                                         cookies = new CookieCollection ();
342                                 return cookies;
343                         }
344                 }
345
346                 public bool HasEntityBody {
347                         get { return (content_length > 0 || is_chunked); }
348                 }
349
350                 public NameValueCollection Headers {
351                         get { return headers; }
352                 }
353
354                 public string HttpMethod {
355                         get { return method; }
356                 }
357
358                 public Stream InputStream {
359                         get { return input_stream; }
360                 }
361
362                 [MonoTODO ("Always returns false")]
363                 public bool IsAuthenticated {
364                         get { return false; }
365                 }
366
367                 public bool IsLocal {
368                         get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
369                 }
370
371                 public bool IsSecureConnection {
372                         get { return context.Connection.IsSecure; } 
373                 }
374
375                 public bool KeepAlive {
376                         get { return false; }
377                 }
378
379                 public IPEndPoint LocalEndPoint {
380                         get { return context.Connection.LocalEndPoint; }
381                 }
382
383                 public Version ProtocolVersion {
384                         get { return version; }
385                 }
386
387                 public NameValueCollection QueryString {
388                         get { return query_string; }
389                 }
390
391                 public string RawUrl {
392                         get { return raw_url; }
393                 }
394
395                 public IPEndPoint RemoteEndPoint {
396                         get { return context.Connection.RemoteEndPoint; }
397                 }
398
399                 public Guid RequestTraceIdentifier {
400                         get { return identifier; }
401                 }
402
403                 public Uri Url {
404                         get { return url; }
405                 }
406
407                 public Uri UrlReferrer {
408                         get { return referrer; }
409                 }
410
411                 public string UserAgent {
412                         get { return headers ["user-agent"]; }
413                 }
414
415                 public string UserHostAddress {
416                         get { return LocalEndPoint.ToString (); }
417                 }
418
419                 public string UserHostName {
420                         get { return headers ["host"]; }
421                 }
422
423                 public string [] UserLanguages {
424                         get { return user_languages; }
425                 }
426
427                 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
428                 {
429                         return null;
430                 }
431 #if SECURITY_DEP
432                 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
433                 {
434                         return null;
435                         // set no_client_certificate once done.
436                 }
437
438                 public X509Certificate2 GetClientCertificate ()
439                 {
440                         // set no_client_certificate once done.
441
442                         // InvalidOp if call in progress.
443                         return null;
444                 }
445 #endif
446         }
447 }
448 #endif
449