2008-03-27 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / class / System.Web / System.Web / HttpRequest.cs
1 //
2 // System.Web.HttpRequest.cs 
3 //
4 // 
5 // Author:
6 //      Miguel de Icaza (miguel@novell.com)
7 //      Gonzalo Paniagua Javier (gonzalo@novell.com)
8 //
9
10 //
11 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32 using System.Text;
33 using System.Collections;
34 using System.Collections.Specialized;
35 using System.IO;
36 using System.Runtime.InteropServices;
37 using System.Security;
38 using System.Security.Permissions;
39 using System.Security.Principal;
40 using System.Web.Configuration;
41 using System.Web.UI;
42 using System.Web.Util;
43 using System.Globalization;
44
45 namespace System.Web {
46         
47         // CAS - no InheritanceDemand here as the class is sealed
48         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
49         public sealed partial class HttpRequest {
50                 HttpWorkerRequest worker_request;
51                 HttpContext context;
52                 WebROCollection query_string_nvc;
53
54                 //
55                 //string filename;
56                 string orig_url = null;
57                 UriBuilder url_components;
58
59                 string client_target;
60
61                 //
62                 // On-demand computed values
63                 //
64                 HttpBrowserCapabilities browser_capabilities;
65                 string file_path, base_virtual_dir, root_virtual_dir;
66                 string content_type;
67                 int content_length = -1;
68                 Encoding encoding;
69                 string current_exe_path;
70                 string physical_path;
71                 string unescaped_path;
72                 string path_info;
73                 WebROCollection all_params;
74                 WebROCollection headers;
75                 Stream input_stream;
76                 InputFilterStream input_filter;
77                 Stream filter;
78                 HttpCookieCollection cookies;
79                 string http_method;
80
81                 WebROCollection form;
82                 HttpFileCollection files;
83                 
84                 ServerVariablesCollection server_variables;
85                 HttpClientCertificate client_cert;
86                 
87                 string request_type;
88                 string [] accept_types;
89                 string [] user_languages;
90                 Uri cached_url;
91                 TempFileStream request_file;
92
93                 readonly static System.Net.IPAddress [] host_addresses;
94                 
95                 // Validations
96                 bool validate_cookies, validate_query_string, validate_form;
97                 bool checked_cookies, checked_query_string, checked_form;
98
99                 readonly static char [] queryTrimChars = {'?'};
100                 
101                 static HttpRequest ()
102                 {
103                         host_addresses = GetLocalHostAddresses ();
104                 }
105                 
106                 public HttpRequest (string filename, string url, string queryString)
107                 {
108                         // warning 169: what are we supposed to do with filename?
109                         
110                         //this.filename = filename;
111
112                         orig_url = url;
113                         url_components = new UriBuilder (url);
114                         url_components.Query = queryString;
115                         
116                         query_string_nvc = new WebROCollection ();
117                         if (queryString != null)
118                                 HttpUtility.ParseQueryString (queryString, Encoding.Default, query_string_nvc);
119                         query_string_nvc.Protect ();
120                 }
121
122                 internal HttpRequest (HttpWorkerRequest worker_request, HttpContext context)
123                 {
124                         this.worker_request = worker_request;
125                         this.context = context;
126                 }
127                 
128                 internal UriBuilder UrlComponents {
129                         get {
130                                 if (url_components == null) {
131                                         string query;
132                                         byte[] queryStringRaw = worker_request.GetQueryStringRawBytes();
133                                         if(queryStringRaw != null)
134                                                 query = ContentEncoding.GetString(queryStringRaw);
135                                         else
136                                                 query = worker_request.GetQueryString();
137                                         
138                                         BuildUrlComponents (
139 #if NET_2_0
140                                                 ApplyUrlMapping (worker_request.GetUriPath ()),
141 #else
142                                                 worker_request.GetUriPath (),
143 #endif
144                                                 query);
145                                 }
146                                 return url_components;
147                         }
148                 }
149
150                 void BuildUrlComponents (string path, string query)
151                 {
152                         if (url_components != null)
153                                 return;
154                         url_components = new UriBuilder ();
155                         url_components.Scheme = worker_request.GetProtocol ();
156                         url_components.Host = worker_request.GetServerName ();
157                         url_components.Port = worker_request.GetLocalPort ();
158                         url_components.Path = path;
159                         if (query != null && query.Length > 0)
160                                 url_components.Query = query.TrimStart (queryTrimChars);
161                 }
162
163 #if NET_2_0
164                 internal string ApplyUrlMapping (string url)
165                 {
166                         if (WebConfigurationManager.HasConfigErrors)
167                                 return url;
168                         
169                         UrlMappingsSection ums = WebConfigurationManager.GetSection ("system.web/urlMappings", ApplicationPath) as UrlMappingsSection;
170                         UrlMappingCollection umc;
171
172                         if (ums == null || !ums.IsEnabled || (umc = ums.UrlMappings).Count == 0)
173                                 return url;
174
175                         string relUrl = VirtualPathUtility.ToAppRelative (url);
176                         UrlMapping um = null;
177                         
178                         foreach (UrlMapping u in umc) {
179                                 if (u == null)
180                                         continue;
181                                 if (String.Compare (relUrl, u.Url, StringComparison.Ordinal) == 0) {
182                                         um = u;
183                                         break;
184                                 }
185                         }
186
187                         if (um == null)
188                                 return url;
189
190                         string rawUrl = VirtualPathUtility.ToAbsolute (um.MappedUrl.Trim ());
191                         Uri newUrl = new Uri ("http://host.com" + rawUrl);
192
193                         if (url_components != null) {
194                                 url_components.Path = newUrl.AbsolutePath;
195                                 url_components.Query = newUrl.Query.TrimStart (queryTrimChars);
196                                 query_string_nvc = new WebROCollection ();
197                                 HttpUtility.ParseQueryString (newUrl.Query, Encoding.Default, query_string_nvc);
198                                 query_string_nvc.Protect ();
199                         } else
200                                 BuildUrlComponents (newUrl.AbsolutePath, newUrl.Query);
201
202                         return url_components.Path;
203                 }
204 #endif
205
206                 string [] SplitHeader (int header_index)
207                 {
208                         string [] result = null;
209                         string header = worker_request.GetKnownRequestHeader (header_index);
210                         if (header != null && header != "" && header.Trim () != "") {
211                                 result = header.Split (',');
212                                 for (int i = result.Length - 1; i >= 0; i--)
213                                         result [i] = result [i].Trim ();
214                         }
215                         return result;
216                 }
217
218                 public string [] AcceptTypes {
219                         get {
220                                 if (worker_request == null)
221                                         return null;
222
223                                 if (accept_types == null)
224                                         accept_types = SplitHeader (HttpWorkerRequest.HeaderAccept);
225
226                                 return accept_types;
227                         }
228                 }
229
230 #if NET_2_0
231 #if !TARGET_JVM
232                 public WindowsIdentity LogonUserIdentity {
233                         get { throw new NotImplementedException (); }
234                 }
235 #endif
236                 
237                 string anonymous_id;
238                 public string AnonymousID {
239                         get {
240                                 return anonymous_id;
241                         }
242                         internal set {
243                                 anonymous_id = value;
244                         }
245                 }
246 #endif
247
248                 public string ApplicationPath {
249                         get {
250                                 if (worker_request == null)
251                                         return null;
252                                 return worker_request.GetAppPath ();
253                         }
254                 }
255
256                 public HttpBrowserCapabilities Browser {
257                         get {
258                                 if (browser_capabilities == null)
259                                         browser_capabilities = (HttpBrowserCapabilities)
260                                                 HttpCapabilitiesBase.GetConfigCapabilities (null, this);
261
262                                 return browser_capabilities;
263                         }
264
265                         set {
266                                 browser_capabilities = value;
267                         }
268                 }
269
270 #if NET_2_0             
271                 internal bool BrowserMightHaveSpecialWriter {
272                         get {
273                                 return (browser_capabilities != null 
274                                         || HttpApplicationFactory.AppBrowsersFiles.Length > 0);
275                         }
276                 }
277
278                 internal bool BrowserMightHaveAdapters {
279                         get {
280                                 return (browser_capabilities != null 
281                                         || HttpApplicationFactory.AppBrowsersFiles.Length > 0);
282                         }
283                 }
284 #endif
285
286                 public HttpClientCertificate ClientCertificate {
287                         get {
288                                 if (client_cert == null)
289                                         client_cert = new HttpClientCertificate (worker_request);
290                                 return client_cert;
291                         }
292                 }
293
294                 static internal string GetParameter (string header, string attr)
295                 {
296                         int ap = header.IndexOf (attr);
297                         if (ap == -1)
298                                 return null;
299
300                         ap += attr.Length;
301                         if (ap >= header.Length)
302                                 return null;
303                         
304                         char ending = header [ap];
305                         if (ending != '"')
306                                 ending = ' ';
307                         
308                         int end = header.IndexOf (ending, ap+1);
309                         if (end == -1)
310                                 return (ending == '"') ? null : header.Substring (ap);
311
312                         return header.Substring (ap+1, end-ap-1);
313                 }
314
315                 public Encoding ContentEncoding {
316                         get {
317                                 if (encoding == null){
318                                         if (worker_request == null)
319                                                 throw new HttpException ("No HttpWorkerRequest");
320                                         
321                                         string content_type = ContentType;
322                                         string parameter = GetParameter (content_type, "; charset=");
323                                         if (parameter == null) {
324                                                 encoding = WebEncoding.RequestEncoding;
325                                         } else {
326                                                 try {
327                                                         // Do what the #1 web server does
328                                                         encoding = Encoding.GetEncoding (parameter);
329                                                 } catch {
330                                                         encoding = WebEncoding.RequestEncoding;
331                                                 }
332                                         }
333                                 }
334                                 return encoding;
335                         }
336
337                         set {
338                                 encoding = value;
339                         }
340                 }
341
342                 public int ContentLength {
343                         get {
344                                 if (content_length == -1){
345                                         if (worker_request == null)
346                                                 return 0;
347
348                                         string cl = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentLength);
349
350                                         if (cl != null) {
351                                                 try {
352                                                         content_length = Int32.Parse (cl);
353                                                 } catch { }
354                                         }
355                                 }
356
357                                 // content_length will still be < 0, but we know we gotta read from the client
358                                 if (content_length < 0)
359                                         return 0;
360
361                                 return content_length;
362                         }
363                 }
364
365                 public string ContentType {
366                         get {
367                                 if (content_type == null){
368                                         if (worker_request != null)
369                                                 content_type = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentType);
370
371                                         if (content_type == null)
372                                                 content_type = String.Empty;
373                                 }
374                                 
375                                 return content_type;
376                         }
377
378                         set {
379                                 content_type = value;
380                         }
381                 }
382
383                 public HttpCookieCollection Cookies {
384                         get {
385                                 if (cookies == null) {
386                                         if (worker_request == null) {
387                                                 cookies = new HttpCookieCollection ();
388                                         } else {
389                                                 string cookie_hv = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderCookie);
390                                                 cookies = new HttpCookieCollection (cookie_hv);
391                                         }
392                                 }
393
394 #if TARGET_J2EE
395                                 // For J2EE portal support we emulate cookies using the session.
396                                 GetSessionCookiesForPortal (cookies);
397 #endif
398                                 if (validate_cookies && !checked_cookies){
399                                         ValidateCookieCollection (cookies);
400                                         checked_cookies = true;
401                                 }
402
403                                 return cookies;
404                         }
405
406                 }
407
408                 public string CurrentExecutionFilePath {
409                         get {
410                                 if (current_exe_path != null)
411                                         return current_exe_path;
412
413                                 return FilePath;
414                         }
415                 }
416
417 #if NET_2_0
418                 public string AppRelativeCurrentExecutionFilePath {
419                         get {
420                                 return VirtualPathUtility.ToAppRelative (CurrentExecutionFilePath);
421                         }
422                 }
423 #endif
424
425                 public string FilePath {
426                         get {
427                                 if (worker_request == null)
428                                         return "/"; // required for 2.0
429
430                                 if (file_path == null)
431                                         file_path = UrlUtils.Canonic (
432 #if NET_2_0
433                                                 ApplyUrlMapping (worker_request.GetFilePath ())
434 #else
435                                                 worker_request.GetFilePath ()
436 #endif
437                                         );
438
439                                 return file_path;
440                         }
441                 }
442
443                 internal string BaseVirtualDir {
444                         get {
445                                 if (base_virtual_dir == null){
446                                         base_virtual_dir = FilePath;
447                                         int p = base_virtual_dir.LastIndexOf ('/');
448                                         if (p != -1)
449                                                 base_virtual_dir = base_virtual_dir.Substring (0, p);
450                                 }
451                                 return base_virtual_dir;
452                         }
453                 }
454                 
455                 public HttpFileCollection Files {
456                         get {
457                                 if (files == null) {
458                                         files = new HttpFileCollection ();
459                                         if ((worker_request != null) && IsContentType ("multipart/form-data", true)) {
460                                                 form = new WebROCollection ();
461                                                 LoadMultiPart ();
462                                                 form.Protect ();
463                                         }
464                                 }
465                                 return files;
466                         }
467                 }
468
469                 public Stream Filter {
470                         get {
471                                 if (filter != null)
472                                         return filter;
473
474                                 if (input_filter == null)
475                                         input_filter = new InputFilterStream ();
476
477                                 return input_filter;
478                         }
479
480                         set {
481                                 // This checks that get_ was called before.
482                                 if (input_filter == null)
483                                         throw new HttpException ("Invalid filter");
484
485                                 filter = value;
486                         }
487                 }
488
489                 // GetSubStream returns a 'copy' of the InputStream with Position set to 0.
490                 static Stream GetSubStream (Stream stream)
491                 {
492 #if !TARGET_JVM
493                         if (stream is IntPtrStream)
494                                 return new IntPtrStream (stream);
495 #endif
496
497                         if (stream is MemoryStream) {
498                                 MemoryStream other = (MemoryStream) stream;
499                                 return new MemoryStream (other.GetBuffer (), 0, (int) other.Length, false, true);
500                         }
501
502                         if (stream is TempFileStream) {
503                                 ((TempFileStream) stream).SavePosition ();
504                                 return stream;
505                         }
506
507                         throw new NotSupportedException ("The stream is " + stream.GetType ());
508                 }
509
510                 static void EndSubStream (Stream stream)
511                 {
512                         if (stream is TempFileStream) {
513                                 ((TempFileStream) stream).RestorePosition ();
514                         }
515                 }
516
517                 //
518                 // Loads the data on the form for multipart/form-data
519                 //
520                 void LoadMultiPart ()
521                 {
522                         string boundary = GetParameter (ContentType, "; boundary=");
523                         if (boundary == null)
524                                 return;
525
526                         Stream input = GetSubStream (InputStream);
527                         HttpMultipart multi_part = new HttpMultipart (input, boundary, ContentEncoding);
528
529                         HttpMultipart.Element e;
530                         while ((e = multi_part.ReadNextElement ()) != null) {
531                                 if (e.Filename == null){
532                                         byte [] copy = new byte [e.Length];
533                                 
534                                         input.Position = e.Start;
535                                         input.Read (copy, 0, (int) e.Length);
536
537                                         form.Add (e.Name, ContentEncoding.GetString (copy));
538                                 } else {
539                                         //
540                                         // We use a substream, as in 2.x we will support large uploads streamed to disk,
541                                         //
542                                         HttpPostedFile sub = new HttpPostedFile (e.Filename, e.ContentType, input, e.Start, e.Length);
543                                         files.AddFile (e.Name, sub);
544                                 }
545                         }
546                         EndSubStream (input);
547                 }
548
549                 //
550                 // Adds the key/value to the form, and sets the argumets to empty
551                 //
552                 void AddRawKeyValue (StringBuilder key, StringBuilder value)
553                 {
554                         string decodedKey = HttpUtility.UrlDecode (key.ToString (), ContentEncoding);
555                         form.Add (decodedKey,
556                                   HttpUtility.UrlDecode (value.ToString (), ContentEncoding));
557
558                         key.Length = 0;
559                         value.Length = 0;
560                 }
561
562                 //
563                 // Loads the form data from on a application/x-www-form-urlencoded post
564                 // 
565 #if TARGET_J2EE
566                 void RawLoadWwwForm ()
567 #else
568                 void LoadWwwForm ()
569 #endif
570                 {
571                         Stream input = GetSubStream (InputStream);
572                         StreamReader s = new StreamReader (input, ContentEncoding);
573
574                         StringBuilder key = new StringBuilder ();
575                         StringBuilder value = new StringBuilder ();
576                         int c;
577
578                         while ((c = s.Read ()) != -1){
579                                 if (c == '='){
580                                         value.Length = 0;
581                                         while ((c = s.Read ()) != -1){
582                                                 if (c == '&'){
583                                                         AddRawKeyValue (key, value);
584                                                         break;
585                                                 } else
586                                                         value.Append ((char) c);
587                                         }
588                                         if (c == -1){
589                                                 AddRawKeyValue (key, value);
590                                                 return;
591                                         }
592                                 } else if (c == '&')
593                                         AddRawKeyValue (key, value);
594                                 else
595                                         key.Append ((char) c);
596                         }
597                         if (c == -1)
598                                 AddRawKeyValue (key, value);
599
600                         EndSubStream (input);
601                 }
602
603                 bool IsContentType (string ct, bool starts_with)
604                 {
605                         if (starts_with)
606                                 return StrUtils.StartsWith (ContentType, ct, true);
607
608                         return String.Compare (ContentType, ct, true, CultureInfo.InvariantCulture) == 0;
609                 }
610                 
611                 public NameValueCollection Form {
612                         get {
613                                 if (form == null){
614                                         form = new WebROCollection ();
615                                         files = new HttpFileCollection ();
616
617                                         if (IsContentType ("multipart/form-data", true))
618                                                 LoadMultiPart ();
619                                         else if (
620                                                 IsContentType ("application/x-www-form-urlencoded", true))
621                                                 LoadWwwForm ();
622
623                                         form.Protect ();
624                                 }
625
626                                 if (validate_form && !checked_form){
627                                         checked_form = true;
628                                         ValidateNameValueCollection ("Form", form);
629                                 }
630                                 
631                                 return form;
632                         }
633                 }
634
635                 public NameValueCollection Headers {
636                         get {
637                                 if (headers == null)
638                                         headers = new HeadersCollection (this);
639                                 
640                                 return headers;
641                         }
642                 }
643
644                 public string HttpMethod {
645                         get {
646                                 if (http_method == null){
647                                         if (worker_request != null)
648                                                 http_method = worker_request.GetHttpVerbName ();
649                                         else
650                                                 http_method = "GET";
651                                 }
652                                 return http_method;
653                         }
654                 }
655
656                 void DoFilter (byte [] buffer)
657                 {
658                         if (input_filter == null || filter == null)
659                                 return;
660
661                         if (buffer.Length < 1024)
662                                 buffer = new byte [1024];
663
664                         // Replace the input with the filtered input
665                         input_filter.BaseStream = input_stream;
666                         MemoryStream ms = new MemoryStream ();
667                         while (true) {
668                                 int n = filter.Read (buffer, 0, buffer.Length);
669                                 if (n <= 0)
670                                         break;
671                                 ms.Write (buffer, 0, n);
672                         }
673                         // From now on input_stream has the filtered input
674                         input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
675                 }
676
677 #if !TARGET_JVM
678                 const int INPUT_BUFFER_SIZE = 32*1024;
679
680                 TempFileStream GetTempStream ()
681                 {
682                         string tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
683                         TempFileStream f = null;
684                         string path;
685                         Random rnd = new Random ();
686                         int num;
687                         do {
688                                 num = rnd.Next ();
689                                 num++;
690                                 path = System.IO.Path.Combine (tempdir, "tmp" + num.ToString("x") + ".req");
691
692                                 try {
693                                         f = new TempFileStream (path);
694                                 } catch (SecurityException) {
695                                         // avoid an endless loop
696                                         throw;
697                                 } catch { }
698                         } while (f == null);
699
700                         return f;
701                 }
702
703                 void MakeInputStream ()
704                 {
705                         if (input_stream != null)
706                                 return;
707
708                         if (worker_request == null) {
709                                 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
710                                 DoFilter (new byte [1024]);
711                                 return;
712                         }
713
714                         //
715                         // Use an unmanaged memory block as this might be a large
716                         // upload
717                         //
718                         int content_length = ContentLength;
719
720 #if NET_2_0
721                         HttpRuntimeSection config = (HttpRuntimeSection) WebConfigurationManager.GetSection ("system.web/httpRuntime");
722 #else
723                         HttpRuntimeConfig config = (HttpRuntimeConfig) HttpContext.GetAppConfig ("system.web/httpRuntime");
724 #endif
725                         if ((content_length / 1024) > config.MaxRequestLength)
726                                 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
727
728                         int total = 0;
729                         byte [] buffer;
730                         buffer = worker_request.GetPreloadedEntityBody ();
731                         // we check the instance field 'content_length' here, not the local var.
732                         if (this.content_length <= 0 || worker_request.IsEntireEntityBodyIsPreloaded ()) {
733                                 if (buffer == null || content_length == 0) {
734                                         input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
735                                 } else {
736                                         input_stream = new MemoryStream (buffer, 0, buffer.Length, false, true);
737                                 }
738                                 DoFilter (new byte [1024]);
739                                 return;
740                         }
741
742                         if (buffer != null)
743                                 total = buffer.Length;
744
745                         if (content_length > 0 && (content_length / 1024) >= config.RequestLengthDiskThreshold) {
746                                 // Writes the request to disk
747                                 total = Math.Min (content_length, total);
748                                 request_file = GetTempStream ();
749                                 Stream output = request_file;
750                                 if (total > 0)
751                                         output.Write (buffer, 0, total);
752
753                                 if (total < content_length) {
754                                         buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
755                                         do {
756                                                 int n;
757                                                 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
758                                                 n = worker_request.ReadEntityBody (buffer, min);
759                                                 if (n <= 0)
760                                                         break;
761                                                 output.Write (buffer, 0, n);
762                                                 total += n;
763                                         } while (total < content_length);
764                                 }
765
766                                 request_file.SetReadOnly ();
767                                 input_stream = request_file;
768                         } else if (content_length > 0) {
769                                 // Buffers the request in an IntPtrStream
770                                 total = Math.Min (content_length, total);
771                                 IntPtr content = Marshal.AllocHGlobal (content_length);
772                                 if (content == (IntPtr) 0)
773                                         throw new HttpException (String.Format ("Not enough memory to allocate {0} bytes.",
774                                                                         content_length));
775
776                                 if (total > 0)
777                                         Marshal.Copy (buffer, 0, content, total);
778
779                                 if (total < content_length) {
780                                         buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
781                                         do {
782                                                 int n;
783                                                 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
784                                                 n = worker_request.ReadEntityBody (buffer, min);
785                                                 if (n <= 0)
786                                                         break;
787                                                 Marshal.Copy (buffer, 0, (IntPtr) ((long)content + total), n);
788                                                 total += n;
789                                         } while (total < content_length);
790                                 }
791
792                                 input_stream = new IntPtrStream (content, total);
793                         } else {
794                                 // Buffers the request in a MemoryStream or writes to disk if threshold exceeded
795                                 MemoryStream ms = new MemoryStream ();
796                                 Stream output = ms;
797                                 if (total > 0)
798                                         ms.Write (buffer, 0, total);
799
800                                 buffer = new byte [INPUT_BUFFER_SIZE];
801                                 long maxlength = config.MaxRequestLength * 1024;
802                                 long disk_th = config.RequestLengthDiskThreshold * 1024;
803                                 int n;
804                                 while (true) {
805                                         n = worker_request.ReadEntityBody (buffer, INPUT_BUFFER_SIZE);
806                                         if (n <= 0)
807                                                 break;
808                                         total += n;
809                                         if (total < 0 || total > maxlength)
810                                                 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
811
812                                         if (ms != null && total > disk_th) {
813                                                 // Swith to on-disk file.
814                                                 request_file = GetTempStream ();
815                                                 ms.WriteTo (request_file);
816                                                 ms = null;
817                                                 output = request_file;
818                                         }
819                                         output.Write (buffer, 0, n);
820                                 }
821
822                                 if (ms != null) {
823                                         input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
824                                 } else {
825                                         request_file.SetReadOnly ();
826                                         input_stream = request_file;
827                                 }
828                         }
829                         DoFilter (buffer);
830
831                         if (total < content_length)
832                                 throw new HttpException (411, "The request body is incomplete.");
833                 }
834 #endif
835
836                 internal void ReleaseResources ()
837                 {
838                         Stream stream;
839                         if (input_stream != null){
840                                 stream = input_stream;
841                                 input_stream = null;
842                                 try {
843                                         stream.Close ();
844                                 } catch {}
845                         }
846
847                         if (request_file != null) {
848                                 stream = request_file;
849                                 request_file = null;
850                                 try {
851                                         stream.Close ();
852                                 } catch {}
853                         }
854                 }
855                 
856                 public Stream InputStream {
857                         get {
858                                 if (input_stream == null)
859                                         MakeInputStream ();
860
861                                 return input_stream;
862                         }
863                 }
864
865                 public bool IsAuthenticated {
866                         get {
867                                 if (context.User == null || context.User.Identity == null)
868                                         return false;
869                                 return context.User.Identity.IsAuthenticated;
870                         }
871                 }
872
873                 public bool IsSecureConnection {
874                         get {
875                                 if (worker_request == null)
876                                         return false;
877                                 return worker_request.IsSecure ();
878                         }
879                 }
880
881                 public string this [string key] {
882                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
883                         get {
884                                 // "The QueryString, Form, Cookies, or ServerVariables collection member
885                                 // specified in the key parameter."
886                                 string val = QueryString [key];
887                                 if (val == null)
888                                         val = Form [key];
889                                 if (val == null) {
890                                         HttpCookie cookie = Cookies [key];
891                                         if (cookie != null)
892                                                 val = cookie.Value;
893                                 }
894                                 if (val == null)
895                                         val = ServerVariables [key];
896
897                                 return val;
898                         }
899                 }
900
901                 public NameValueCollection Params {
902                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
903                         get {
904                                 if (all_params == null)
905                                         all_params = new HttpParamsCollection (QueryString, Form, ServerVariables, Cookies);
906
907                                 return all_params;
908                         }
909                 }
910
911                 public string Path {
912                         get {
913                                 if (unescaped_path == null) {
914                                         string path;
915                                         if (url_components != null) {
916                                                 // use only if it's already been instantiated, so that we can't go into endless
917                                                 // recursion in some scenarios
918                                                 path = UrlComponents.Path;
919                                         } else {
920 #if NET_2_0
921                                                 path = ApplyUrlMapping (worker_request.GetUriPath ());
922 #else
923                                                 path = worker_request.GetUriPath ();
924 #endif
925                                         }
926                                                 
927 #if NET_2_0
928                                         unescaped_path = Uri.UnescapeDataString (path);
929 #else
930                                         unescaped_path = HttpUtility.UrlDecode (path);
931 #endif
932                                 }
933                                 
934                                 return unescaped_path;
935                         }
936                 }
937
938                 public string PathInfo {
939                         get {
940                                 if (path_info == null) {
941                                         if (worker_request == null)
942                                                 return String.Empty;
943                                         path_info = worker_request.GetPathInfo ();
944                                 }
945
946                                 return path_info;
947                         }
948                 }
949
950                 public string PhysicalApplicationPath {
951                         get {
952                                 if (worker_request == null)
953                                         throw new ArgumentNullException (); // like 2.0, 1.x throws TypeInitializationException
954
955                                 string path = HttpRuntime.AppDomainAppPath;
956                                 if (SecurityManager.SecurityEnabled) {
957                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
958                                 }
959                                 return path;
960                         }
961                 }
962
963                 public string PhysicalPath {
964                         get {
965                                 if (worker_request == null)
966                                         return String.Empty; // don't check security with an empty string!
967
968                                 if (physical_path == null) {
969                                         // Don't call HttpRequest.MapPath here, as that one *trims* the input
970                                         physical_path = worker_request.MapPath (FilePath);
971                                 }
972
973                                 if (SecurityManager.SecurityEnabled) {
974                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, physical_path).Demand ();
975                                 }
976                                 return physical_path;
977                         }
978                 }
979
980                 internal string RootVirtualDir {
981                         get {
982                                 if (root_virtual_dir == null){
983                                         string fp = FilePath;
984                                         int p = fp.LastIndexOf ('/');
985
986                                         if (p < 1)
987                                                 root_virtual_dir = "/";
988                                         else
989                                                 root_virtual_dir = fp.Substring (0, p);
990                                 }
991                                 return root_virtual_dir;
992                         }
993                 }
994
995                 public NameValueCollection QueryString {
996                         get {
997                                 if (query_string_nvc == null) {
998                                         query_string_nvc = new WebROCollection ();
999                                         string q = UrlComponents.Query;
1000                                         if (q != null) {
1001                                                 if (q.Length != 0)
1002                                                         q = q.Remove(0, 1);
1003                                         
1004                                                 HttpUtility.ParseQueryString (q, ContentEncoding, query_string_nvc);
1005                                         }
1006                                         
1007                                         query_string_nvc.Protect();
1008                                 }
1009                                 
1010                                 if (validate_query_string && !checked_query_string) {
1011                                         ValidateNameValueCollection ("QueryString", query_string_nvc);
1012                                         checked_query_string = true;
1013                                 }
1014                                 
1015                                 return query_string_nvc;
1016                         }
1017                 }
1018
1019                 public string RawUrl {
1020                         get {
1021                                 if (worker_request != null)
1022                                         return worker_request.GetRawUrl ();
1023                                 else
1024                                         return UrlComponents.Path + UrlComponents.Query;
1025                         }
1026                 }
1027
1028                 //
1029                 // "GET" or "SET"
1030                 //
1031                 public string RequestType {
1032                         get {
1033                                 if (request_type == null){
1034                                         if (worker_request != null) {
1035                                                 request_type = worker_request.GetHttpVerbName ();
1036                                                 http_method = request_type;
1037                                         } else {
1038                                                 request_type = "GET";
1039                                         }
1040                                 }
1041                                 return request_type;
1042                         }
1043
1044                         set {
1045                                 request_type = value;
1046                         }
1047                 }
1048
1049                 public NameValueCollection ServerVariables {
1050                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
1051                         get {
1052                                 if (server_variables == null)
1053                                         server_variables = new ServerVariablesCollection (this);
1054
1055                                 return server_variables;
1056                         }
1057                 }
1058
1059                 public int TotalBytes {
1060                         get {
1061                                 Stream ins = InputStream;
1062                                 return (int) ins.Length;
1063                         }
1064                 }
1065
1066                 public Uri Url {
1067                         get {
1068                                 if (cached_url == null) {
1069                                         if (orig_url == null)
1070                                                 cached_url = UrlComponents.Uri;
1071                                         else
1072                                                 cached_url = new Uri (orig_url);
1073                                 }
1074
1075                                 return cached_url;                      
1076                         }
1077                 }
1078
1079                 public Uri UrlReferrer {
1080                         get {
1081                                 if (worker_request == null)
1082                                         return null;
1083
1084                                 string hr = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderReferer);
1085                                 if (hr == null)
1086                                         return null;
1087
1088                                 Uri uri = null;
1089                                 try {
1090                                         uri = new Uri (hr);
1091                                 } catch (UriFormatException) {}
1092                                 return uri;
1093                         }
1094                 }
1095
1096                 public string UserAgent {
1097                         get {
1098                                 if (worker_request == null)
1099                                         return null;
1100
1101                                 return worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderUserAgent);
1102                         }
1103                 }
1104
1105                 public string UserHostAddress {
1106                         get {
1107                                 if (worker_request == null)
1108                                         return null;
1109
1110                                 return worker_request.GetRemoteAddress ();
1111                         }
1112                 }
1113
1114                 public string UserHostName {
1115                         get {
1116                                 if (worker_request == null)
1117                                         return null;
1118
1119                                 return worker_request.GetRemoteName ();
1120                         }
1121                 }
1122
1123                 public string [] UserLanguages {
1124                         get {
1125                                 if (worker_request == null)
1126                                         return null;
1127
1128                                 if (user_languages == null)
1129                                         user_languages = SplitHeader (HttpWorkerRequest.HeaderAcceptLanguage);
1130
1131                                 return user_languages;
1132                         }
1133                 }
1134
1135                 public byte [] BinaryRead (int count)
1136                 {
1137                         if (count < 0)
1138                                 throw new ArgumentException ("count is < 0");
1139
1140                         Stream s = InputStream;
1141                         byte [] ret = new byte [count];
1142                         if (s.Read (ret, 0, count) != count)
1143                                 throw new ArgumentException (
1144                                         String.Format ("count {0} exceeds length of available input {1}",
1145                                                 count, s.Length - s.Position));
1146                         return ret;
1147                 }
1148
1149                 public int [] MapImageCoordinates (string imageFieldName)
1150                 {
1151                         string method = HttpMethod;
1152                         NameValueCollection coll = null;
1153                         if (method == "HEAD" || method == "GET")
1154                                 coll = QueryString;
1155                         else if (method == "POST")
1156                                 coll = Form;
1157
1158                         if (coll == null)
1159                                 return null;
1160
1161                         string x = coll [imageFieldName + ".x"];
1162                         if (x == null || x == "")
1163                                 return null;
1164
1165                         string y = coll [imageFieldName + ".y"];
1166                         if (y == null || y == "")
1167                                 return null;
1168
1169                         int [] result = new int [2];
1170                         try {
1171                                 result [0] = Int32.Parse (x);
1172                                 result [1] = Int32.Parse (y);
1173                         } catch {
1174                                 return null;
1175                         }
1176
1177                         return result;
1178                 }
1179
1180                 public string MapPath (string virtualPath)
1181                 {
1182                         if (worker_request == null)
1183                                 return null;
1184
1185                         return MapPath (virtualPath, BaseVirtualDir, true);
1186                 }
1187
1188                 public string MapPath (string virtualPath, string baseVirtualDir, bool allowCrossAppMapping)
1189                 {
1190                         if (worker_request == null)
1191                                 throw new HttpException ("No HttpWorkerRequest");
1192
1193                         if (virtualPath == null)
1194                                 virtualPath = "~";
1195                         else {
1196                                 virtualPath = virtualPath.Trim ();
1197                                 if (virtualPath.Length == 0)
1198                                         virtualPath = "~";
1199                         }
1200
1201                         if (virtualPath.IndexOf (':') != -1)
1202                                 throw new HttpException (String.Format ("'{0}' is not a valid virtual path.", virtualPath));
1203
1204                         string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
1205
1206                         if (!VirtualPathUtility.IsRooted (virtualPath)) {
1207                                 if (StrUtils.IsNullOrEmpty (baseVirtualDir))
1208                                         baseVirtualDir = appVirtualPath;
1209                                 virtualPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (baseVirtualDir), virtualPath);
1210                         }
1211                         virtualPath = VirtualPathUtility.ToAbsolute (virtualPath);
1212                         
1213                         if (!allowCrossAppMapping){
1214                                 if (!StrUtils.StartsWith (virtualPath, appVirtualPath, true))
1215                                         throw new HttpException ("MapPath: Mapping across applications not allowed");
1216                                 if (appVirtualPath.Length > 1 && virtualPath.Length > 1 && virtualPath [0] != '/')
1217                                         throw new HttpException ("MapPath: Mapping across applications not allowed");
1218                         }
1219 #if TARGET_JVM
1220                         return worker_request.MapPath (virtualPath);
1221 #else
1222                         string path = worker_request.MapPath (virtualPath);
1223                         if (virtualPath [virtualPath.Length - 1] != '/' && path [path.Length - 1] == System.IO.Path.DirectorySeparatorChar)
1224                                 path = path.TrimEnd (System.IO.Path.DirectorySeparatorChar);
1225                         return path;
1226 #endif
1227                 }
1228
1229                 public void SaveAs (string filename, bool includeHeaders)
1230                 {
1231                         Stream output = new FileStream (filename, FileMode.Create);
1232                         if (includeHeaders) {
1233                                 StringBuilder sb = new StringBuilder ();
1234                                 string version = String.Empty;
1235                                 string path = "/";
1236                                 if (worker_request != null) {
1237                                         version = worker_request.GetHttpVersion ();
1238                                         path = UrlComponents.Path;
1239                                 }
1240                                 string qs = UrlComponents.Query;
1241
1242                                 sb.AppendFormat ("{0} {1}{2} {3}\r\n", HttpMethod, path, qs, version);
1243                                 NameValueCollection coll = Headers;
1244                                 foreach (string k in coll.AllKeys) {
1245                                         sb.Append (k);
1246                                         sb.Append (':');
1247                                         sb.Append (coll [k]);
1248                                         sb.Append ("\r\n");
1249                                 }
1250                                 sb.Append ("\r\n");
1251                                 // latin1
1252                                 byte [] bytes = Encoding.GetEncoding (28591).GetBytes (sb.ToString ());
1253                                 output.Write (bytes, 0, bytes.Length);
1254                         }
1255
1256                         // More than 1 call to SaveAs works fine on MS, so we "copy" the stream
1257                         // to keep InputStream in its state.
1258                         Stream input = GetSubStream (InputStream);
1259                         try {
1260                                 long len = input.Length;
1261                                 int buf_size = (int) Math.Min ((len < 0 ? 0 : len), 8192);
1262                                 byte [] data = new byte [buf_size];
1263                                 int count = 0;
1264                                 while (len > 0 && (count = input.Read (data, 0, buf_size)) > 0) {
1265                                         output.Write (data, 0, count);
1266                                         len -= count;
1267                                 }
1268                         } finally {
1269                                 output.Flush ();
1270                                 output.Close ();
1271                                 EndSubStream (input);
1272                         }
1273                 }
1274
1275                 public void ValidateInput ()
1276                 {
1277                         validate_cookies = true;
1278                         validate_query_string = true;
1279                         validate_form = true;
1280                 }
1281
1282 #region internal routines
1283                 internal string ClientTarget {
1284                         get {
1285                                 return client_target;
1286                         }
1287
1288                         set {
1289                                 client_target = value;
1290                         }
1291                 }
1292
1293 #if NET_2_0
1294                 public
1295 #else
1296                 internal
1297 #endif
1298                 bool IsLocal {
1299                         get {
1300                                 string address = worker_request.GetRemoteAddress ();
1301
1302                                 if (StrUtils.IsNullOrEmpty (address))
1303                                         return false;
1304
1305                                 if (address == "127.0.0.1")
1306                                         return true;
1307
1308                                 System.Net.IPAddress remoteAddr = System.Net.IPAddress.Parse (address);
1309                                 if (System.Net.IPAddress.IsLoopback (remoteAddr))
1310                                         return true;
1311
1312                                 for (int i = 0; i < host_addresses.Length; i++)
1313                                         if (remoteAddr.Equals (host_addresses [i]))
1314                                                 return true;
1315
1316                                 return false;
1317                         }
1318                 }
1319
1320                 internal void SetFilePath (string path)
1321                 {
1322                         file_path = path;
1323                         physical_path = null;
1324                 }
1325
1326                 internal void SetCurrentExePath (string path)
1327                 {
1328                         cached_url = null;
1329                         current_exe_path = path;
1330                         UrlComponents.Path = path;
1331                         // recreated on demand
1332                         root_virtual_dir = null;
1333                         base_virtual_dir = null;
1334                         physical_path = null;
1335                         unescaped_path = null;
1336                 }
1337
1338                 internal void SetPathInfo (string pi)
1339                 {
1340                         cached_url = null;
1341                         path_info = pi;
1342                 }
1343
1344                 // Headers is ReadOnly, so we need this hack for cookie-less sessions.
1345                 internal void SetHeader (string name, string value)
1346                 {
1347                         WebROCollection h = (WebROCollection) Headers;
1348                         h.Unprotect ();
1349                         h [name] = value;
1350                         h.Protect ();
1351                 }
1352
1353                 // Notice: there is nothing raw about this querystring.
1354                 internal string QueryStringRaw {
1355                         get {
1356                                 if (url_components == null)
1357                                         return worker_request.GetQueryString ();
1358
1359                                 return UrlComponents.Query;
1360                         }
1361
1362                         set {
1363                                 UrlComponents.Query = value;
1364                                 cached_url = null;
1365                                 query_string_nvc = null;
1366                         }
1367                 }
1368
1369                 // Internal, dont know what it does, so flagged as public so we can see it.
1370                 internal void SetForm (WebROCollection coll)
1371                 {
1372                         form = coll;
1373                 }
1374
1375                 internal HttpWorkerRequest WorkerRequest {
1376                         get {
1377                                 return worker_request;
1378                         }
1379                 }
1380
1381                 internal HttpContext Context {
1382                         get {
1383                                 return context;
1384                         }
1385                 }
1386
1387                 static void ValidateNameValueCollection (string name, NameValueCollection coll)
1388                 {
1389                         if (coll == null)
1390                                 return;
1391                 
1392                         foreach (string key in coll.Keys) {
1393                                 string val = coll [key];
1394                                 if (val != null && val != "" && CheckString (val))
1395                                         ThrowValidationException (name, key, val);
1396                         }
1397                 }
1398                 
1399                 static void ValidateCookieCollection (HttpCookieCollection cookies)
1400                 {
1401                         if (cookies == null)
1402                                 return;
1403                 
1404                         int size = cookies.Count;
1405                         HttpCookie cookie;
1406                         for (int i = 0 ; i < size ; i++) {
1407                                 cookie = cookies[i];
1408                                 string value = cookie.Value;
1409                                 
1410                                 if (value != null && value != "" && CheckString (value))
1411                                         ThrowValidationException ("Cookies", cookie.Name, cookie.Value);
1412                         }
1413                 }
1414                 
1415                 static void ThrowValidationException (string name, string key, string value)
1416                 {
1417                         string v = "\"" + value + "\"";
1418                         if (v.Length > 20)
1419                                 v = v.Substring (0, 16) + "...\"";
1420                 
1421                         string msg = String.Format ("A potentially dangerous Request.{0} value was " +
1422                                                     "detected from the client ({1}={2}).", name, key, v);
1423                 
1424                         throw new HttpRequestValidationException (msg);
1425                 }
1426                 
1427                 static bool CheckString (string val)
1428                 {
1429                         int len = val.Length;
1430                         if (len < 2)
1431                                 return false;
1432
1433                         char current = val [0];
1434                         for (int idx = 1; idx < len; idx++) {
1435                                 char next = val [idx];
1436                                 if (current == '<' || current == '\xff1c') {
1437                                         if (next == '!' || next < ' '
1438                                             || (next >= 'a' && next <= 'z')
1439                                             || (next >= 'A' && next <= 'Z'))
1440                                                 return true;
1441                                 } else if (current == '&' && next == '#') {
1442                                         return true;
1443                                 }
1444
1445                                 current = next;
1446                         }
1447
1448                         return false;
1449                 }
1450
1451                 static System.Net.IPAddress [] GetLocalHostAddresses ()
1452                 {
1453                         try {
1454                                 string hostName = System.Net.Dns.GetHostName ();
1455 #if NET_2_0
1456                                 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostAddresses (hostName);
1457 #else
1458                                 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostByName (hostName).AddressList;
1459 #endif
1460                                 return ipaddr;
1461                         }
1462                         catch
1463                         {
1464                                 return new System.Net.IPAddress[0];
1465                         }
1466                 }
1467         }
1468 #endregion
1469
1470 #region Helper classes
1471         
1472         //
1473         // Stream-based multipart handling.
1474         //
1475         // In this incarnation deals with an HttpInputStream as we are now using
1476         // IntPtr-based streams instead of byte [].   In the future, we will also
1477         // send uploads above a certain threshold into the disk (to implement
1478         // limit-less HttpInputFiles). 
1479         //
1480         
1481         class HttpMultipart {
1482
1483                 public class Element {
1484                         public string ContentType;
1485                         public string Name;
1486                         public string Filename;
1487                         public long Start;
1488                         public long Length;
1489                         
1490                         public override string ToString ()
1491                         {
1492                                 return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
1493                                         Start.ToString () + ", Length " + Length.ToString ();
1494                         }
1495                 }
1496                 
1497                 Stream data;
1498                 string boundary;
1499                 byte [] boundary_bytes;
1500                 byte [] buffer;
1501                 bool at_eof;
1502                 Encoding encoding;
1503                 StringBuilder sb;
1504                 
1505                 const byte HYPHEN = (byte) '-', LF = (byte) '\n', CR = (byte) '\r';
1506                 
1507                 // See RFC 2046 
1508                 // In the case of multipart entities, in which one or more different
1509                 // sets of data are combined in a single body, a "multipart" media type
1510                 // field must appear in the entity's header.  The body must then contain
1511                 // one or more body parts, each preceded by a boundary delimiter line,
1512                 // and the last one followed by a closing boundary delimiter line.
1513                 // After its boundary delimiter line, each body part then consists of a
1514                 // header area, a blank line, and a body area.  Thus a body part is
1515                 // similar to an RFC 822 message in syntax, but different in meaning.
1516                 
1517                 public HttpMultipart (Stream data, string b, Encoding encoding)
1518                 {
1519                         this.data = data;
1520                         boundary = b;
1521                         boundary_bytes = encoding.GetBytes (b);
1522                         buffer = new byte [boundary_bytes.Length + 2]; // CRLF or '--'
1523                         this.encoding = encoding;
1524                         sb = new StringBuilder ();
1525                 }
1526
1527                 string ReadLine ()
1528                 {
1529                         // CRLF or LF are ok as line endings.
1530                         bool got_cr = false;
1531                         int b = 0;
1532                         sb.Length = 0;
1533                         while (true) {
1534                                 b = data.ReadByte ();
1535                                 if (b == -1) {
1536                                         return null;
1537                                 }
1538
1539                                 if (b == LF) {
1540                                         break;
1541                                 }
1542                                 got_cr = (b == CR);
1543                                 sb.Append ((char) b);
1544                         }
1545
1546                         if (got_cr)
1547                                 sb.Length--;
1548
1549                         return sb.ToString ();
1550
1551                 }
1552
1553                 static string GetContentDispositionAttribute (string l, string name)
1554                 {
1555                         int idx = l.IndexOf (name + "=\"");
1556                         if (idx < 0)
1557                                 return null;
1558                         int begin = idx + name.Length + "=\"".Length;
1559                         int end = l.IndexOf ('"', begin);
1560                         if (end < 0)
1561                                 return null;
1562                         if (begin == end)
1563                                 return "";
1564                         return l.Substring (begin, end - begin);
1565                 }
1566
1567                 string GetContentDispositionAttributeWithEncoding (string l, string name)
1568                 {
1569                         int idx = l.IndexOf (name + "=\"");
1570                         if (idx < 0)
1571                                 return null;
1572                         int begin = idx + name.Length + "=\"".Length;
1573                         int end = l.IndexOf ('"', begin);
1574                         if (end < 0)
1575                                 return null;
1576                         if (begin == end)
1577                                 return "";
1578
1579                         string temp = l.Substring (begin, end - begin);
1580                         byte [] source = new byte [temp.Length];
1581                         for (int i = temp.Length - 1; i >= 0; i--)
1582                                 source [i] = (byte) temp [i];
1583
1584                         return encoding.GetString (source);
1585                 }
1586
1587                 bool ReadBoundary ()
1588                 {
1589                         try {
1590                                 string line = ReadLine ();
1591                                 while (line == "")
1592                                         line = ReadLine ();
1593                                 if (line [0] != '-' || line [1] != '-')
1594                                         return false;
1595
1596                                 if (!StrUtils.EndsWith (line, boundary, false))
1597                                         return true;
1598                         } catch {
1599                         }
1600
1601                         return false;
1602                 }
1603
1604                 string ReadHeaders ()
1605                 {
1606                         string s = ReadLine ();
1607                         if (s == "")
1608                                 return null;
1609
1610                         return s;
1611                 }
1612
1613                 bool CompareBytes (byte [] orig, byte [] other)
1614                 {
1615                         for (int i = orig.Length - 1; i >= 0; i--)
1616                                 if (orig [i] != other [i])
1617                                         return false;
1618
1619                         return true;
1620                 }
1621
1622                 long MoveToNextBoundary ()
1623                 {
1624                         long retval = 0;
1625                         bool got_cr = false;
1626
1627                         int state = 0;
1628                         int c = data.ReadByte ();
1629                         while (true) {
1630                                 if (c == -1)
1631                                         return -1;
1632
1633                                 if (state == 0 && c == LF) {
1634                                         retval = data.Position - 1;
1635                                         if (got_cr)
1636                                                 retval--;
1637                                         state = 1;
1638                                         c = data.ReadByte ();
1639                                 } else if (state == 0) {
1640                                         got_cr = (c == CR);
1641                                         c = data.ReadByte ();
1642                                 } else if (state == 1 && c == '-') {
1643                                         c = data.ReadByte ();
1644                                         if (c == -1)
1645                                                 return -1;
1646
1647                                         if (c != '-') {
1648                                                 state = 0;
1649                                                 got_cr = false;
1650                                                 continue; // no ReadByte() here
1651                                         }
1652
1653                                         int nread = data.Read (buffer, 0, buffer.Length);
1654                                         int bl = buffer.Length;
1655                                         if (nread != bl)
1656                                                 return -1;
1657
1658                                         if (!CompareBytes (boundary_bytes, buffer)) {
1659                                                 state = 0;
1660                                                 data.Position = retval + 2;
1661                                                 if (got_cr) {
1662                                                         data.Position++;
1663                                                         got_cr = false;
1664                                                 }
1665                                                 c = data.ReadByte ();
1666                                                 continue;
1667                                         }
1668
1669                                         if (buffer [bl - 2] == '-' && buffer [bl - 1] == '-') {
1670                                                 at_eof = true;
1671                                         } else if (buffer [bl - 2] != CR || buffer [bl - 1] != LF) {
1672                                                 state = 0;
1673                                                 data.Position = retval + 2;
1674                                                 if (got_cr) {
1675                                                         data.Position++;
1676                                                         got_cr = false;
1677                                                 }
1678                                                 c = data.ReadByte ();
1679                                                 continue;
1680                                         }
1681                                         data.Position = retval + 2;
1682                                         if (got_cr)
1683                                                 data.Position++;
1684                                         break;
1685                                 } else {
1686                                         // state == 1
1687                                         state = 0; // no ReadByte() here
1688                                 }
1689                         }
1690
1691                         return retval;
1692                 }
1693
1694                 public Element ReadNextElement ()
1695                 {
1696                         if (at_eof || ReadBoundary ())
1697                                 return null;
1698
1699                         Element elem = new Element ();
1700                         string header;
1701                         while ((header = ReadHeaders ()) != null) {
1702                                 if (StrUtils.StartsWith (header, "Content-Disposition:", true)) {
1703                                         elem.Name = GetContentDispositionAttribute (header, "name");
1704                                         elem.Filename = StripPath (GetContentDispositionAttributeWithEncoding (header, "filename"));
1705                                 } else if (StrUtils.StartsWith (header, "Content-Type:", true)) {
1706                                         elem.ContentType = header.Substring ("Content-Type:".Length).Trim ();
1707                                 }
1708                         }
1709
1710                         long start = data.Position;
1711                         elem.Start = start;
1712                         long pos = MoveToNextBoundary ();
1713                         if (pos == -1)
1714                                 return null;
1715
1716                         elem.Length = pos - start;
1717                         return elem;
1718                 }
1719
1720                 static string StripPath (string path)
1721                 {
1722                         if (path == null || path.Length == 0)
1723                                 return path;
1724                         
1725                         if (path.IndexOf (":\\") != 1)
1726                                 return path;
1727                         return path.Substring (path.LastIndexOf ("\\") + 1);
1728                 }
1729         }
1730 #endregion
1731 }
1732