2008-04-23 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                         using (Stream input = GetSubStream (InputStream)) {
572                                 using (StreamReader s = new StreamReader (input, ContentEncoding)) {
573                                         StringBuilder key = new StringBuilder ();
574                                         StringBuilder value = new StringBuilder ();
575                                         int c;
576
577                                         while ((c = s.Read ()) != -1){
578                                                 if (c == '='){
579                                                         value.Length = 0;
580                                                         while ((c = s.Read ()) != -1){
581                                                                 if (c == '&'){
582                                                                         AddRawKeyValue (key, value);
583                                                                         break;
584                                                                 } else
585                                                                         value.Append ((char) c);
586                                                         }
587                                                         if (c == -1){
588                                                                 AddRawKeyValue (key, value);
589                                                                 return;
590                                                         }
591                                                 } else if (c == '&')
592                                                         AddRawKeyValue (key, value);
593                                                 else
594                                                         key.Append ((char) c);
595                                         }
596                                         if (c == -1)
597                                                 AddRawKeyValue (key, value);
598
599                                         EndSubStream (input);
600                                 }
601                         }
602                 }
603
604                 bool IsContentType (string ct, bool starts_with)
605                 {
606                         if (starts_with)
607                                 return StrUtils.StartsWith (ContentType, ct, true);
608
609                         return String.Compare (ContentType, ct, true, CultureInfo.InvariantCulture) == 0;
610                 }
611                 
612                 public NameValueCollection Form {
613                         get {
614                                 if (form == null){
615                                         form = new WebROCollection ();
616                                         files = new HttpFileCollection ();
617
618                                         if (IsContentType ("multipart/form-data", true))
619                                                 LoadMultiPart ();
620                                         else if (
621                                                 IsContentType ("application/x-www-form-urlencoded", true))
622                                                 LoadWwwForm ();
623
624                                         form.Protect ();
625                                 }
626
627                                 if (validate_form && !checked_form){
628                                         checked_form = true;
629                                         ValidateNameValueCollection ("Form", form);
630                                 }
631                                 
632                                 return form;
633                         }
634                 }
635
636                 public NameValueCollection Headers {
637                         get {
638                                 if (headers == null)
639                                         headers = new HeadersCollection (this);
640                                 
641                                 return headers;
642                         }
643                 }
644
645                 public string HttpMethod {
646                         get {
647                                 if (http_method == null){
648                                         if (worker_request != null)
649                                                 http_method = worker_request.GetHttpVerbName ();
650                                         else
651                                                 http_method = "GET";
652                                 }
653                                 return http_method;
654                         }
655                 }
656
657                 void DoFilter (byte [] buffer)
658                 {
659                         if (input_filter == null || filter == null)
660                                 return;
661
662                         if (buffer.Length < 1024)
663                                 buffer = new byte [1024];
664
665                         // Replace the input with the filtered input
666                         input_filter.BaseStream = input_stream;
667                         MemoryStream ms = new MemoryStream ();
668                         while (true) {
669                                 int n = filter.Read (buffer, 0, buffer.Length);
670                                 if (n <= 0)
671                                         break;
672                                 ms.Write (buffer, 0, n);
673                         }
674                         // From now on input_stream has the filtered input
675                         input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
676                 }
677
678 #if !TARGET_JVM
679                 const int INPUT_BUFFER_SIZE = 32*1024;
680
681                 TempFileStream GetTempStream ()
682                 {
683                         string tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
684                         TempFileStream f = null;
685                         string path;
686                         Random rnd = new Random ();
687                         int num;
688                         do {
689                                 num = rnd.Next ();
690                                 num++;
691                                 path = System.IO.Path.Combine (tempdir, "tmp" + num.ToString("x") + ".req");
692
693                                 try {
694                                         f = new TempFileStream (path);
695                                 } catch (SecurityException) {
696                                         // avoid an endless loop
697                                         throw;
698                                 } catch { }
699                         } while (f == null);
700
701                         return f;
702                 }
703
704                 void MakeInputStream ()
705                 {
706                         if (input_stream != null)
707                                 return;
708
709                         if (worker_request == null) {
710                                 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
711                                 DoFilter (new byte [1024]);
712                                 return;
713                         }
714
715                         //
716                         // Use an unmanaged memory block as this might be a large
717                         // upload
718                         //
719                         int content_length = ContentLength;
720
721 #if NET_2_0
722                         HttpRuntimeSection config = (HttpRuntimeSection) WebConfigurationManager.GetSection ("system.web/httpRuntime");
723 #else
724                         HttpRuntimeConfig config = (HttpRuntimeConfig) HttpContext.GetAppConfig ("system.web/httpRuntime");
725 #endif
726                         if ((content_length / 1024) > config.MaxRequestLength)
727                                 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
728
729                         int total = 0;
730                         byte [] buffer;
731                         buffer = worker_request.GetPreloadedEntityBody ();
732                         // we check the instance field 'content_length' here, not the local var.
733                         if (this.content_length <= 0 || worker_request.IsEntireEntityBodyIsPreloaded ()) {
734                                 if (buffer == null || content_length == 0) {
735                                         input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
736                                 } else {
737                                         input_stream = new MemoryStream (buffer, 0, buffer.Length, false, true);
738                                 }
739                                 DoFilter (new byte [1024]);
740                                 return;
741                         }
742
743                         if (buffer != null)
744                                 total = buffer.Length;
745
746                         if (content_length > 0 && (content_length / 1024) >= config.RequestLengthDiskThreshold) {
747                                 // Writes the request to disk
748                                 total = Math.Min (content_length, total);
749                                 request_file = GetTempStream ();
750                                 Stream output = request_file;
751                                 if (total > 0)
752                                         output.Write (buffer, 0, total);
753
754                                 if (total < content_length) {
755                                         buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
756                                         do {
757                                                 int n;
758                                                 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
759                                                 n = worker_request.ReadEntityBody (buffer, min);
760                                                 if (n <= 0)
761                                                         break;
762                                                 output.Write (buffer, 0, n);
763                                                 total += n;
764                                         } while (total < content_length);
765                                 }
766
767                                 request_file.SetReadOnly ();
768                                 input_stream = request_file;
769                         } else if (content_length > 0) {
770                                 // Buffers the request in an IntPtrStream
771                                 total = Math.Min (content_length, total);
772                                 IntPtr content = Marshal.AllocHGlobal (content_length);
773                                 if (content == (IntPtr) 0)
774                                         throw new HttpException (String.Format ("Not enough memory to allocate {0} bytes.",
775                                                                         content_length));
776
777                                 if (total > 0)
778                                         Marshal.Copy (buffer, 0, content, total);
779
780                                 if (total < content_length) {
781                                         buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
782                                         do {
783                                                 int n;
784                                                 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
785                                                 n = worker_request.ReadEntityBody (buffer, min);
786                                                 if (n <= 0)
787                                                         break;
788                                                 Marshal.Copy (buffer, 0, (IntPtr) ((long)content + total), n);
789                                                 total += n;
790                                         } while (total < content_length);
791                                 }
792
793                                 input_stream = new IntPtrStream (content, total);
794                         } else {
795                                 // Buffers the request in a MemoryStream or writes to disk if threshold exceeded
796                                 MemoryStream ms = new MemoryStream ();
797                                 Stream output = ms;
798                                 if (total > 0)
799                                         ms.Write (buffer, 0, total);
800
801                                 buffer = new byte [INPUT_BUFFER_SIZE];
802                                 long maxlength = config.MaxRequestLength * 1024;
803                                 long disk_th = config.RequestLengthDiskThreshold * 1024;
804                                 int n;
805                                 while (true) {
806                                         n = worker_request.ReadEntityBody (buffer, INPUT_BUFFER_SIZE);
807                                         if (n <= 0)
808                                                 break;
809                                         total += n;
810                                         if (total < 0 || total > maxlength)
811                                                 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
812
813                                         if (ms != null && total > disk_th) {
814                                                 // Swith to on-disk file.
815                                                 request_file = GetTempStream ();
816                                                 ms.WriteTo (request_file);
817                                                 ms = null;
818                                                 output = request_file;
819                                         }
820                                         output.Write (buffer, 0, n);
821                                 }
822
823                                 if (ms != null) {
824                                         input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
825                                 } else {
826                                         request_file.SetReadOnly ();
827                                         input_stream = request_file;
828                                 }
829                         }
830                         DoFilter (buffer);
831
832                         if (total < content_length)
833                                 throw new HttpException (411, "The request body is incomplete.");
834                 }
835 #endif
836
837                 internal void ReleaseResources ()
838                 {
839                         Stream stream;
840                         if (input_stream != null){
841                                 stream = input_stream;
842                                 input_stream = null;
843                                 try {
844                                         stream.Close ();
845                                 } catch {}
846                         }
847
848                         if (request_file != null) {
849                                 stream = request_file;
850                                 request_file = null;
851                                 try {
852                                         stream.Close ();
853                                 } catch {}
854                         }
855                 }
856                 
857                 public Stream InputStream {
858                         get {
859                                 if (input_stream == null)
860                                         MakeInputStream ();
861
862                                 return input_stream;
863                         }
864                 }
865
866                 public bool IsAuthenticated {
867                         get {
868                                 if (context.User == null || context.User.Identity == null)
869                                         return false;
870                                 return context.User.Identity.IsAuthenticated;
871                         }
872                 }
873
874                 public bool IsSecureConnection {
875                         get {
876                                 if (worker_request == null)
877                                         return false;
878                                 return worker_request.IsSecure ();
879                         }
880                 }
881
882                 public string this [string key] {
883                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
884                         get {
885                                 // "The QueryString, Form, Cookies, or ServerVariables collection member
886                                 // specified in the key parameter."
887                                 string val = QueryString [key];
888                                 if (val == null)
889                                         val = Form [key];
890                                 if (val == null) {
891                                         HttpCookie cookie = Cookies [key];
892                                         if (cookie != null)
893                                                 val = cookie.Value;
894                                 }
895                                 if (val == null)
896                                         val = ServerVariables [key];
897
898                                 return val;
899                         }
900                 }
901
902                 public NameValueCollection Params {
903                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
904                         get {
905                                 if (all_params == null)
906                                         all_params = new HttpParamsCollection (QueryString, Form, ServerVariables, Cookies);
907
908                                 return all_params;
909                         }
910                 }
911
912                 public string Path {
913                         get {
914                                 if (unescaped_path == null) {
915                                         string path;
916                                         if (url_components != null) {
917                                                 // use only if it's already been instantiated, so that we can't go into endless
918                                                 // recursion in some scenarios
919                                                 path = UrlComponents.Path;
920                                         } else {
921 #if NET_2_0
922                                                 path = ApplyUrlMapping (worker_request.GetUriPath ());
923 #else
924                                                 path = worker_request.GetUriPath ();
925 #endif
926                                         }
927                                                 
928 #if NET_2_0
929                                         unescaped_path = Uri.UnescapeDataString (path);
930 #else
931                                         unescaped_path = HttpUtility.UrlDecode (path);
932 #endif
933                                 }
934                                 
935                                 return unescaped_path;
936                         }
937                 }
938
939                 public string PathInfo {
940                         get {
941                                 if (path_info == null) {
942                                         if (worker_request == null)
943                                                 return String.Empty;
944                                         path_info = worker_request.GetPathInfo ();
945                                 }
946
947                                 return path_info;
948                         }
949                 }
950
951                 public string PhysicalApplicationPath {
952                         get {
953                                 if (worker_request == null)
954                                         throw new ArgumentNullException (); // like 2.0, 1.x throws TypeInitializationException
955
956                                 string path = HttpRuntime.AppDomainAppPath;
957                                 if (SecurityManager.SecurityEnabled) {
958                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
959                                 }
960                                 return path;
961                         }
962                 }
963
964                 public string PhysicalPath {
965                         get {
966                                 if (worker_request == null)
967                                         return String.Empty; // don't check security with an empty string!
968
969                                 if (physical_path == null) {
970                                         // Don't call HttpRequest.MapPath here, as that one *trims* the input
971                                         physical_path = worker_request.MapPath (FilePath);
972                                 }
973
974                                 if (SecurityManager.SecurityEnabled) {
975                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, physical_path).Demand ();
976                                 }
977                                 return physical_path;
978                         }
979                 }
980
981                 internal string RootVirtualDir {
982                         get {
983                                 if (root_virtual_dir == null){
984                                         string fp = FilePath;
985                                         int p = fp.LastIndexOf ('/');
986
987                                         if (p < 1)
988                                                 root_virtual_dir = "/";
989                                         else
990                                                 root_virtual_dir = fp.Substring (0, p);
991                                 }
992                                 return root_virtual_dir;
993                         }
994                 }
995
996                 public NameValueCollection QueryString {
997                         get {
998                                 if (query_string_nvc == null) {
999                                         query_string_nvc = new WebROCollection ();
1000                                         string q = UrlComponents.Query;
1001                                         if (q != null) {
1002                                                 if (q.Length != 0)
1003                                                         q = q.Remove(0, 1);
1004                                         
1005                                                 HttpUtility.ParseQueryString (q, ContentEncoding, query_string_nvc);
1006                                         }
1007                                         
1008                                         query_string_nvc.Protect();
1009                                 }
1010                                 
1011                                 if (validate_query_string && !checked_query_string) {
1012                                         ValidateNameValueCollection ("QueryString", query_string_nvc);
1013                                         checked_query_string = true;
1014                                 }
1015                                 
1016                                 return query_string_nvc;
1017                         }
1018                 }
1019
1020                 public string RawUrl {
1021                         get {
1022                                 if (worker_request != null)
1023                                         return worker_request.GetRawUrl ();
1024                                 else
1025                                         return UrlComponents.Path + UrlComponents.Query;
1026                         }
1027                 }
1028
1029                 //
1030                 // "GET" or "SET"
1031                 //
1032                 public string RequestType {
1033                         get {
1034                                 if (request_type == null){
1035                                         if (worker_request != null) {
1036                                                 request_type = worker_request.GetHttpVerbName ();
1037                                                 http_method = request_type;
1038                                         } else {
1039                                                 request_type = "GET";
1040                                         }
1041                                 }
1042                                 return request_type;
1043                         }
1044
1045                         set {
1046                                 request_type = value;
1047                         }
1048                 }
1049
1050                 public NameValueCollection ServerVariables {
1051                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
1052                         get {
1053                                 if (server_variables == null)
1054                                         server_variables = new ServerVariablesCollection (this);
1055
1056                                 return server_variables;
1057                         }
1058                 }
1059
1060                 public int TotalBytes {
1061                         get {
1062                                 Stream ins = InputStream;
1063                                 return (int) ins.Length;
1064                         }
1065                 }
1066
1067                 public Uri Url {
1068                         get {
1069                                 if (cached_url == null) {
1070                                         if (orig_url == null)
1071                                                 cached_url = UrlComponents.Uri;
1072                                         else
1073                                                 cached_url = new Uri (orig_url);
1074                                 }
1075
1076                                 return cached_url;                      
1077                         }
1078                 }
1079
1080                 public Uri UrlReferrer {
1081                         get {
1082                                 if (worker_request == null)
1083                                         return null;
1084
1085                                 string hr = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderReferer);
1086                                 if (hr == null)
1087                                         return null;
1088
1089                                 Uri uri = null;
1090                                 try {
1091                                         uri = new Uri (hr);
1092                                 } catch (UriFormatException) {}
1093                                 return uri;
1094                         }
1095                 }
1096
1097                 public string UserAgent {
1098                         get {
1099                                 if (worker_request == null)
1100                                         return null;
1101
1102                                 return worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderUserAgent);
1103                         }
1104                 }
1105
1106                 public string UserHostAddress {
1107                         get {
1108                                 if (worker_request == null)
1109                                         return null;
1110
1111                                 return worker_request.GetRemoteAddress ();
1112                         }
1113                 }
1114
1115                 public string UserHostName {
1116                         get {
1117                                 if (worker_request == null)
1118                                         return null;
1119
1120                                 return worker_request.GetRemoteName ();
1121                         }
1122                 }
1123
1124                 public string [] UserLanguages {
1125                         get {
1126                                 if (worker_request == null)
1127                                         return null;
1128
1129                                 if (user_languages == null)
1130                                         user_languages = SplitHeader (HttpWorkerRequest.HeaderAcceptLanguage);
1131
1132                                 return user_languages;
1133                         }
1134                 }
1135
1136                 public byte [] BinaryRead (int count)
1137                 {
1138                         if (count < 0)
1139                                 throw new ArgumentException ("count is < 0");
1140
1141                         Stream s = InputStream;
1142                         byte [] ret = new byte [count];
1143                         if (s.Read (ret, 0, count) != count)
1144                                 throw new ArgumentException (
1145                                         String.Format ("count {0} exceeds length of available input {1}",
1146                                                 count, s.Length - s.Position));
1147                         return ret;
1148                 }
1149
1150                 public int [] MapImageCoordinates (string imageFieldName)
1151                 {
1152                         string method = HttpMethod;
1153                         NameValueCollection coll = null;
1154                         if (method == "HEAD" || method == "GET")
1155                                 coll = QueryString;
1156                         else if (method == "POST")
1157                                 coll = Form;
1158
1159                         if (coll == null)
1160                                 return null;
1161
1162                         string x = coll [imageFieldName + ".x"];
1163                         if (x == null || x == "")
1164                                 return null;
1165
1166                         string y = coll [imageFieldName + ".y"];
1167                         if (y == null || y == "")
1168                                 return null;
1169
1170                         int [] result = new int [2];
1171                         try {
1172                                 result [0] = Int32.Parse (x);
1173                                 result [1] = Int32.Parse (y);
1174                         } catch {
1175                                 return null;
1176                         }
1177
1178                         return result;
1179                 }
1180
1181                 public string MapPath (string virtualPath)
1182                 {
1183                         if (worker_request == null)
1184                                 return null;
1185
1186                         return MapPath (virtualPath, BaseVirtualDir, true);
1187                 }
1188
1189                 public string MapPath (string virtualPath, string baseVirtualDir, bool allowCrossAppMapping)
1190                 {
1191                         if (worker_request == null)
1192                                 throw new HttpException ("No HttpWorkerRequest");
1193
1194                         if (virtualPath == null)
1195                                 virtualPath = "~";
1196                         else {
1197                                 virtualPath = virtualPath.Trim ();
1198                                 if (virtualPath.Length == 0)
1199                                         virtualPath = "~";
1200                         }
1201
1202                         if (virtualPath.IndexOf (':') != -1)
1203                                 throw new HttpException (String.Format ("'{0}' is not a valid virtual path.", virtualPath));
1204
1205                         string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
1206
1207                         if (!VirtualPathUtility.IsRooted (virtualPath)) {
1208                                 if (StrUtils.IsNullOrEmpty (baseVirtualDir))
1209                                         baseVirtualDir = appVirtualPath;
1210                                 virtualPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (baseVirtualDir), virtualPath);
1211                         }
1212                         virtualPath = VirtualPathUtility.ToAbsolute (virtualPath);
1213                         
1214                         if (!allowCrossAppMapping){
1215                                 if (!StrUtils.StartsWith (virtualPath, appVirtualPath, true))
1216                                         throw new HttpException ("MapPath: Mapping across applications not allowed");
1217                                 if (appVirtualPath.Length > 1 && virtualPath.Length > 1 && virtualPath [0] != '/')
1218                                         throw new HttpException ("MapPath: Mapping across applications not allowed");
1219                         }
1220 #if TARGET_JVM
1221                         return worker_request.MapPath (virtualPath);
1222 #else
1223                         string path = worker_request.MapPath (virtualPath);
1224                         if (virtualPath [virtualPath.Length - 1] != '/' && path [path.Length - 1] == System.IO.Path.DirectorySeparatorChar)
1225                                 path = path.TrimEnd (System.IO.Path.DirectorySeparatorChar);
1226                         return path;
1227 #endif
1228                 }
1229
1230                 public void SaveAs (string filename, bool includeHeaders)
1231                 {
1232                         Stream output = new FileStream (filename, FileMode.Create);
1233                         if (includeHeaders) {
1234                                 StringBuilder sb = new StringBuilder ();
1235                                 string version = String.Empty;
1236                                 string path = "/";
1237                                 if (worker_request != null) {
1238                                         version = worker_request.GetHttpVersion ();
1239                                         path = UrlComponents.Path;
1240                                 }
1241                                 string qs = UrlComponents.Query;
1242
1243                                 sb.AppendFormat ("{0} {1}{2} {3}\r\n", HttpMethod, path, qs, version);
1244                                 NameValueCollection coll = Headers;
1245                                 foreach (string k in coll.AllKeys) {
1246                                         sb.Append (k);
1247                                         sb.Append (':');
1248                                         sb.Append (coll [k]);
1249                                         sb.Append ("\r\n");
1250                                 }
1251                                 sb.Append ("\r\n");
1252                                 // latin1
1253                                 byte [] bytes = Encoding.GetEncoding (28591).GetBytes (sb.ToString ());
1254                                 output.Write (bytes, 0, bytes.Length);
1255                         }
1256
1257                         // More than 1 call to SaveAs works fine on MS, so we "copy" the stream
1258                         // to keep InputStream in its state.
1259                         Stream input = GetSubStream (InputStream);
1260                         try {
1261                                 long len = input.Length;
1262                                 int buf_size = (int) Math.Min ((len < 0 ? 0 : len), 8192);
1263                                 byte [] data = new byte [buf_size];
1264                                 int count = 0;
1265                                 while (len > 0 && (count = input.Read (data, 0, buf_size)) > 0) {
1266                                         output.Write (data, 0, count);
1267                                         len -= count;
1268                                 }
1269                         } finally {
1270                                 output.Flush ();
1271                                 output.Close ();
1272                                 EndSubStream (input);
1273                         }
1274                 }
1275
1276                 public void ValidateInput ()
1277                 {
1278                         validate_cookies = true;
1279                         validate_query_string = true;
1280                         validate_form = true;
1281                 }
1282
1283 #region internal routines
1284                 internal string ClientTarget {
1285                         get {
1286                                 return client_target;
1287                         }
1288
1289                         set {
1290                                 client_target = value;
1291                         }
1292                 }
1293
1294 #if NET_2_0
1295                 public
1296 #else
1297                 internal
1298 #endif
1299                 bool IsLocal {
1300                         get {
1301                                 string address = worker_request.GetRemoteAddress ();
1302
1303                                 if (StrUtils.IsNullOrEmpty (address))
1304                                         return false;
1305
1306                                 if (address == "127.0.0.1")
1307                                         return true;
1308
1309                                 System.Net.IPAddress remoteAddr = System.Net.IPAddress.Parse (address);
1310                                 if (System.Net.IPAddress.IsLoopback (remoteAddr))
1311                                         return true;
1312
1313                                 for (int i = 0; i < host_addresses.Length; i++)
1314                                         if (remoteAddr.Equals (host_addresses [i]))
1315                                                 return true;
1316
1317                                 return false;
1318                         }
1319                 }
1320
1321                 internal void SetFilePath (string path)
1322                 {
1323                         file_path = path;
1324                         physical_path = null;
1325                 }
1326
1327                 internal void SetCurrentExePath (string path)
1328                 {
1329                         cached_url = null;
1330                         current_exe_path = path;
1331                         UrlComponents.Path = path;
1332                         // recreated on demand
1333                         root_virtual_dir = null;
1334                         base_virtual_dir = null;
1335                         physical_path = null;
1336                         unescaped_path = null;
1337                 }
1338
1339                 internal void SetPathInfo (string pi)
1340                 {
1341                         cached_url = null;
1342                         path_info = pi;
1343                 }
1344
1345                 // Headers is ReadOnly, so we need this hack for cookie-less sessions.
1346                 internal void SetHeader (string name, string value)
1347                 {
1348                         WebROCollection h = (WebROCollection) Headers;
1349                         h.Unprotect ();
1350                         h [name] = value;
1351                         h.Protect ();
1352                 }
1353
1354                 // Notice: there is nothing raw about this querystring.
1355                 internal string QueryStringRaw {
1356                         get {
1357                                 UriBuilder urlComponents = UrlComponents;
1358
1359                                 if (urlComponents == null) {
1360                                         string ret = worker_request.GetQueryString ();
1361
1362                                         if (ret == null || ret.Length == 0)
1363                                                 return String.Empty;
1364
1365                                         if (ret [0] == '?')
1366                                                 return ret;
1367
1368                                         return "?" + ret;
1369                                 }
1370                                 
1371                                 return UrlComponents.Query;
1372                         }
1373
1374                         set {
1375                                 UrlComponents.Query = value;
1376                                 cached_url = null;
1377                                 query_string_nvc = null;
1378                         }
1379                 }
1380
1381                 // Internal, dont know what it does, so flagged as public so we can see it.
1382                 internal void SetForm (WebROCollection coll)
1383                 {
1384                         form = coll;
1385                 }
1386
1387                 internal HttpWorkerRequest WorkerRequest {
1388                         get {
1389                                 return worker_request;
1390                         }
1391                 }
1392
1393                 internal HttpContext Context {
1394                         get {
1395                                 return context;
1396                         }
1397                 }
1398
1399                 static void ValidateNameValueCollection (string name, NameValueCollection coll)
1400                 {
1401                         if (coll == null)
1402                                 return;
1403                 
1404                         foreach (string key in coll.Keys) {
1405                                 string val = coll [key];
1406                                 if (val != null && val != "" && CheckString (val))
1407                                         ThrowValidationException (name, key, val);
1408                         }
1409                 }
1410                 
1411                 static void ValidateCookieCollection (HttpCookieCollection cookies)
1412                 {
1413                         if (cookies == null)
1414                                 return;
1415                 
1416                         int size = cookies.Count;
1417                         HttpCookie cookie;
1418                         for (int i = 0 ; i < size ; i++) {
1419                                 cookie = cookies[i];
1420                                 string value = cookie.Value;
1421                                 
1422                                 if (value != null && value != "" && CheckString (value))
1423                                         ThrowValidationException ("Cookies", cookie.Name, cookie.Value);
1424                         }
1425                 }
1426                 
1427                 static void ThrowValidationException (string name, string key, string value)
1428                 {
1429                         string v = "\"" + value + "\"";
1430                         if (v.Length > 20)
1431                                 v = v.Substring (0, 16) + "...\"";
1432                 
1433                         string msg = String.Format ("A potentially dangerous Request.{0} value was " +
1434                                                     "detected from the client ({1}={2}).", name, key, v);
1435                 
1436                         throw new HttpRequestValidationException (msg);
1437                 }
1438                 
1439                 static bool CheckString (string val)
1440                 {
1441                         int len = val.Length;
1442                         if (len < 2)
1443                                 return false;
1444
1445                         char current = val [0];
1446                         for (int idx = 1; idx < len; idx++) {
1447                                 char next = val [idx];
1448                                 if (current == '<' || current == '\xff1c') {
1449                                         if (next == '!' || next < ' '
1450                                             || (next >= 'a' && next <= 'z')
1451                                             || (next >= 'A' && next <= 'Z'))
1452                                                 return true;
1453                                 } else if (current == '&' && next == '#') {
1454                                         return true;
1455                                 }
1456
1457                                 current = next;
1458                         }
1459
1460                         return false;
1461                 }
1462
1463                 static System.Net.IPAddress [] GetLocalHostAddresses ()
1464                 {
1465                         try {
1466                                 string hostName = System.Net.Dns.GetHostName ();
1467 #if NET_2_0
1468                                 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostAddresses (hostName);
1469 #else
1470                                 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostByName (hostName).AddressList;
1471 #endif
1472                                 return ipaddr;
1473                         }
1474                         catch
1475                         {
1476                                 return new System.Net.IPAddress[0];
1477                         }
1478                 }
1479         }
1480 #endregion
1481
1482 #region Helper classes
1483         
1484         //
1485         // Stream-based multipart handling.
1486         //
1487         // In this incarnation deals with an HttpInputStream as we are now using
1488         // IntPtr-based streams instead of byte [].   In the future, we will also
1489         // send uploads above a certain threshold into the disk (to implement
1490         // limit-less HttpInputFiles). 
1491         //
1492         
1493         class HttpMultipart {
1494
1495                 public class Element {
1496                         public string ContentType;
1497                         public string Name;
1498                         public string Filename;
1499                         public long Start;
1500                         public long Length;
1501                         
1502                         public override string ToString ()
1503                         {
1504                                 return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
1505                                         Start.ToString () + ", Length " + Length.ToString ();
1506                         }
1507                 }
1508                 
1509                 Stream data;
1510                 string boundary;
1511                 byte [] boundary_bytes;
1512                 byte [] buffer;
1513                 bool at_eof;
1514                 Encoding encoding;
1515                 StringBuilder sb;
1516                 
1517                 const byte HYPHEN = (byte) '-', LF = (byte) '\n', CR = (byte) '\r';
1518                 
1519                 // See RFC 2046 
1520                 // In the case of multipart entities, in which one or more different
1521                 // sets of data are combined in a single body, a "multipart" media type
1522                 // field must appear in the entity's header.  The body must then contain
1523                 // one or more body parts, each preceded by a boundary delimiter line,
1524                 // and the last one followed by a closing boundary delimiter line.
1525                 // After its boundary delimiter line, each body part then consists of a
1526                 // header area, a blank line, and a body area.  Thus a body part is
1527                 // similar to an RFC 822 message in syntax, but different in meaning.
1528                 
1529                 public HttpMultipart (Stream data, string b, Encoding encoding)
1530                 {
1531                         this.data = data;
1532                         boundary = b;
1533                         boundary_bytes = encoding.GetBytes (b);
1534                         buffer = new byte [boundary_bytes.Length + 2]; // CRLF or '--'
1535                         this.encoding = encoding;
1536                         sb = new StringBuilder ();
1537                 }
1538
1539                 string ReadLine ()
1540                 {
1541                         // CRLF or LF are ok as line endings.
1542                         bool got_cr = false;
1543                         int b = 0;
1544                         sb.Length = 0;
1545                         while (true) {
1546                                 b = data.ReadByte ();
1547                                 if (b == -1) {
1548                                         return null;
1549                                 }
1550
1551                                 if (b == LF) {
1552                                         break;
1553                                 }
1554                                 got_cr = (b == CR);
1555                                 sb.Append ((char) b);
1556                         }
1557
1558                         if (got_cr)
1559                                 sb.Length--;
1560
1561                         return sb.ToString ();
1562
1563                 }
1564
1565                 static string GetContentDispositionAttribute (string l, string name)
1566                 {
1567                         int idx = l.IndexOf (name + "=\"");
1568                         if (idx < 0)
1569                                 return null;
1570                         int begin = idx + name.Length + "=\"".Length;
1571                         int end = l.IndexOf ('"', begin);
1572                         if (end < 0)
1573                                 return null;
1574                         if (begin == end)
1575                                 return "";
1576                         return l.Substring (begin, end - begin);
1577                 }
1578
1579                 string GetContentDispositionAttributeWithEncoding (string l, string name)
1580                 {
1581                         int idx = l.IndexOf (name + "=\"");
1582                         if (idx < 0)
1583                                 return null;
1584                         int begin = idx + name.Length + "=\"".Length;
1585                         int end = l.IndexOf ('"', begin);
1586                         if (end < 0)
1587                                 return null;
1588                         if (begin == end)
1589                                 return "";
1590
1591                         string temp = l.Substring (begin, end - begin);
1592                         byte [] source = new byte [temp.Length];
1593                         for (int i = temp.Length - 1; i >= 0; i--)
1594                                 source [i] = (byte) temp [i];
1595
1596                         return encoding.GetString (source);
1597                 }
1598
1599                 bool ReadBoundary ()
1600                 {
1601                         try {
1602                                 string line = ReadLine ();
1603                                 while (line == "")
1604                                         line = ReadLine ();
1605                                 if (line [0] != '-' || line [1] != '-')
1606                                         return false;
1607
1608                                 if (!StrUtils.EndsWith (line, boundary, false))
1609                                         return true;
1610                         } catch {
1611                         }
1612
1613                         return false;
1614                 }
1615
1616                 string ReadHeaders ()
1617                 {
1618                         string s = ReadLine ();
1619                         if (s == "")
1620                                 return null;
1621
1622                         return s;
1623                 }
1624
1625                 bool CompareBytes (byte [] orig, byte [] other)
1626                 {
1627                         for (int i = orig.Length - 1; i >= 0; i--)
1628                                 if (orig [i] != other [i])
1629                                         return false;
1630
1631                         return true;
1632                 }
1633
1634                 long MoveToNextBoundary ()
1635                 {
1636                         long retval = 0;
1637                         bool got_cr = false;
1638
1639                         int state = 0;
1640                         int c = data.ReadByte ();
1641                         while (true) {
1642                                 if (c == -1)
1643                                         return -1;
1644
1645                                 if (state == 0 && c == LF) {
1646                                         retval = data.Position - 1;
1647                                         if (got_cr)
1648                                                 retval--;
1649                                         state = 1;
1650                                         c = data.ReadByte ();
1651                                 } else if (state == 0) {
1652                                         got_cr = (c == CR);
1653                                         c = data.ReadByte ();
1654                                 } else if (state == 1 && c == '-') {
1655                                         c = data.ReadByte ();
1656                                         if (c == -1)
1657                                                 return -1;
1658
1659                                         if (c != '-') {
1660                                                 state = 0;
1661                                                 got_cr = false;
1662                                                 continue; // no ReadByte() here
1663                                         }
1664
1665                                         int nread = data.Read (buffer, 0, buffer.Length);
1666                                         int bl = buffer.Length;
1667                                         if (nread != bl)
1668                                                 return -1;
1669
1670                                         if (!CompareBytes (boundary_bytes, buffer)) {
1671                                                 state = 0;
1672                                                 data.Position = retval + 2;
1673                                                 if (got_cr) {
1674                                                         data.Position++;
1675                                                         got_cr = false;
1676                                                 }
1677                                                 c = data.ReadByte ();
1678                                                 continue;
1679                                         }
1680
1681                                         if (buffer [bl - 2] == '-' && buffer [bl - 1] == '-') {
1682                                                 at_eof = true;
1683                                         } else if (buffer [bl - 2] != CR || buffer [bl - 1] != LF) {
1684                                                 state = 0;
1685                                                 data.Position = retval + 2;
1686                                                 if (got_cr) {
1687                                                         data.Position++;
1688                                                         got_cr = false;
1689                                                 }
1690                                                 c = data.ReadByte ();
1691                                                 continue;
1692                                         }
1693                                         data.Position = retval + 2;
1694                                         if (got_cr)
1695                                                 data.Position++;
1696                                         break;
1697                                 } else {
1698                                         // state == 1
1699                                         state = 0; // no ReadByte() here
1700                                 }
1701                         }
1702
1703                         return retval;
1704                 }
1705
1706                 public Element ReadNextElement ()
1707                 {
1708                         if (at_eof || ReadBoundary ())
1709                                 return null;
1710
1711                         Element elem = new Element ();
1712                         string header;
1713                         while ((header = ReadHeaders ()) != null) {
1714                                 if (StrUtils.StartsWith (header, "Content-Disposition:", true)) {
1715                                         elem.Name = GetContentDispositionAttribute (header, "name");
1716                                         elem.Filename = StripPath (GetContentDispositionAttributeWithEncoding (header, "filename"));
1717                                 } else if (StrUtils.StartsWith (header, "Content-Type:", true)) {
1718                                         elem.ContentType = header.Substring ("Content-Type:".Length).Trim ();
1719                                 }
1720                         }
1721
1722                         long start = data.Position;
1723                         elem.Start = start;
1724                         long pos = MoveToNextBoundary ();
1725                         if (pos == -1)
1726                                 return null;
1727
1728                         elem.Length = pos - start;
1729                         return elem;
1730                 }
1731
1732                 static string StripPath (string path)
1733                 {
1734                         if (path == null || path.Length == 0)
1735                                 return path;
1736                         
1737                         if (path.IndexOf (":\\") != 1)
1738                                 return path;
1739                         return path.Substring (path.LastIndexOf ("\\") + 1);
1740                 }
1741         }
1742 #endregion
1743 }
1744