2 // System.Web.HttpRequest.cs
6 // Miguel de Icaza (miguel@novell.com)
7 // Gonzalo Paniagua Javier (gonzalo@novell.com)
11 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
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:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
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.
33 using System.Collections;
34 using System.Collections.Specialized;
36 using System.Runtime.InteropServices;
37 using System.Security;
38 using System.Security.Permissions;
39 using System.Web.Configuration;
41 using System.Web.Util;
42 using System.Globalization;
44 namespace System.Web {
46 // CAS - no InheritanceDemand here as the class is sealed
47 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
48 public sealed partial class HttpRequest {
49 HttpWorkerRequest worker_request;
51 WebROCollection query_string_nvc;
55 string orig_url = null;
56 UriBuilder url_components;
61 // On-demand computed values
63 HttpBrowserCapabilities browser_capabilities;
64 string file_path, base_virtual_dir, root_virtual_dir;
66 int content_length = -1;
68 string current_exe_path;
70 string unescaped_path;
72 WebROCollection all_params;
73 WebROCollection headers;
75 InputFilterStream input_filter;
77 HttpCookieCollection cookies;
81 HttpFileCollection files;
83 ServerVariablesCollection server_variables;
84 HttpClientCertificate client_cert;
87 string [] accept_types;
88 string [] user_languages;
90 TempFileStream request_file;
92 readonly static System.Net.IPAddress [] host_addresses;
95 bool validate_cookies, validate_query_string, validate_form;
96 bool checked_cookies, checked_query_string, checked_form;
98 readonly static char [] queryTrimChars = {'?'};
100 static HttpRequest ()
102 host_addresses = GetLocalHostAddresses ();
105 public HttpRequest (string filename, string url, string queryString)
107 // warning 169: what are we supposed to do with filename?
109 //this.filename = filename;
112 url_components = new UriBuilder (url);
113 url_components.Query = queryString;
115 query_string_nvc = new WebROCollection ();
116 if (queryString != null)
117 HttpUtility.ParseQueryString (queryString, Encoding.Default, query_string_nvc);
118 query_string_nvc.Protect ();
121 internal HttpRequest (HttpWorkerRequest worker_request, HttpContext context)
123 this.worker_request = worker_request;
124 this.context = context;
127 UriBuilder UrlComponents {
129 if (url_components == null) {
131 byte[] queryStringRaw = worker_request.GetQueryStringRawBytes();
132 if(queryStringRaw != null)
133 query = ContentEncoding.GetString(queryStringRaw);
135 query = worker_request.GetQueryString();
139 ApplyUrlMapping (worker_request.GetUriPath ()),
141 worker_request.GetUriPath (),
145 return url_components;
149 void BuildUrlComponents (string path, string query)
151 if (url_components != null)
153 url_components = new UriBuilder ();
154 url_components.Scheme = worker_request.GetProtocol ();
155 url_components.Host = worker_request.GetServerName ();
156 url_components.Port = worker_request.GetLocalPort ();
157 url_components.Path = path;
158 if (query != null && query.Length > 0)
159 url_components.Query = query.TrimStart (queryTrimChars);
163 internal string ApplyUrlMapping (string url)
165 if (WebConfigurationManager.HasConfigErrors)
168 UrlMappingsSection ums = WebConfigurationManager.GetSection ("system.web/urlMappings", ApplicationPath) as UrlMappingsSection;
169 UrlMappingCollection umc;
171 if (ums == null || !ums.IsEnabled || (umc = ums.UrlMappings).Count == 0)
174 string relUrl = VirtualPathUtility.ToAppRelative (url);
175 UrlMapping um = null;
177 foreach (UrlMapping u in umc) {
180 if (String.Compare (relUrl, u.Url, StringComparison.Ordinal) == 0) {
189 string rawUrl = VirtualPathUtility.ToAbsolute (um.MappedUrl.Trim ());
190 Uri newUrl = new Uri ("http://host.com" + rawUrl);
192 if (url_components != null) {
193 url_components.Path = newUrl.AbsolutePath;
194 url_components.Query = newUrl.Query.TrimStart (queryTrimChars);
195 query_string_nvc = new WebROCollection ();
196 HttpUtility.ParseQueryString (newUrl.Query, Encoding.Default, query_string_nvc);
197 query_string_nvc.Protect ();
199 BuildUrlComponents (newUrl.AbsolutePath, newUrl.Query);
201 return url_components.Path;
205 string [] SplitHeader (int header_index)
207 string [] result = null;
208 string header = worker_request.GetKnownRequestHeader (header_index);
209 if (header != null && header != "" && header.Trim () != "") {
210 result = header.Split (',');
211 for (int i = result.Length - 1; i >= 0; i--)
212 result [i] = result [i].Trim ();
217 public string [] AcceptTypes {
219 if (worker_request == null)
222 if (accept_types == null)
223 accept_types = SplitHeader (HttpWorkerRequest.HeaderAccept);
231 public string AnonymousID {
236 anonymous_id = value;
241 public string ApplicationPath {
243 if (worker_request == null)
245 return worker_request.GetAppPath ();
249 public HttpBrowserCapabilities Browser {
251 if (browser_capabilities == null)
252 browser_capabilities = (HttpBrowserCapabilities)
253 HttpCapabilitiesBase.GetConfigCapabilities (null, this);
255 return browser_capabilities;
259 browser_capabilities = value;
263 public HttpClientCertificate ClientCertificate {
265 if (client_cert == null)
266 client_cert = new HttpClientCertificate (worker_request);
271 static internal string GetParameter (string header, string attr)
273 int ap = header.IndexOf (attr);
278 if (ap >= header.Length)
281 char ending = header [ap];
285 int end = header.IndexOf (ending, ap+1);
287 return (ending == '"') ? null : header.Substring (ap);
289 return header.Substring (ap+1, end-ap-1);
292 public Encoding ContentEncoding {
294 if (encoding == null){
295 if (worker_request == null)
296 throw new HttpException ("No HttpWorkerRequest");
298 string content_type = ContentType;
299 string parameter = GetParameter (content_type, "; charset=");
300 if (parameter == null) {
301 encoding = WebEncoding.RequestEncoding;
304 // Do what the #1 web server does
305 encoding = Encoding.GetEncoding (parameter);
307 encoding = WebEncoding.RequestEncoding;
319 public int ContentLength {
321 if (content_length == -1){
322 if (worker_request == null)
325 string cl = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentLength);
329 content_length = Int32.Parse (cl);
334 // content_length will still be < 0, but we know we gotta read from the client
335 if (content_length < 0)
338 return content_length;
342 public string ContentType {
344 if (content_type == null){
345 if (worker_request != null)
346 content_type = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentType);
348 if (content_type == null)
349 content_type = String.Empty;
356 content_type = value;
360 public HttpCookieCollection Cookies {
362 if (cookies == null) {
363 if (worker_request == null) {
364 cookies = new HttpCookieCollection ();
366 string cookie_hv = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderCookie);
367 cookies = new HttpCookieCollection (cookie_hv);
372 // For J2EE portal support we emulate cookies using the session.
373 GetSessionCookiesForPortal (cookies);
375 if (validate_cookies && !checked_cookies){
376 ValidateCookieCollection (cookies);
377 checked_cookies = true;
385 public string CurrentExecutionFilePath {
387 if (current_exe_path != null)
388 return current_exe_path;
395 public string AppRelativeCurrentExecutionFilePath {
397 return VirtualPathUtility.ToAppRelative (CurrentExecutionFilePath);
402 public string FilePath {
404 if (worker_request == null)
405 return "/"; // required for 2.0
407 if (file_path == null)
408 file_path = UrlUtils.Canonic (
410 ApplyUrlMapping (worker_request.GetFilePath ())
412 worker_request.GetFilePath ()
420 internal string BaseVirtualDir {
422 if (base_virtual_dir == null){
423 base_virtual_dir = FilePath;
424 int p = base_virtual_dir.LastIndexOf ('/');
426 base_virtual_dir = base_virtual_dir.Substring (0, p);
428 return base_virtual_dir;
432 public HttpFileCollection Files {
435 files = new HttpFileCollection ();
436 if ((worker_request != null) && IsContentType ("multipart/form-data", true)) {
437 form = new WebROCollection ();
446 public Stream Filter {
451 if (input_filter == null)
452 input_filter = new InputFilterStream ();
458 // This checks that get_ was called before.
459 if (input_filter == null)
460 throw new HttpException ("Invalid filter");
466 // GetSubStream returns a 'copy' of the InputStream with Position set to 0.
467 static Stream GetSubStream (Stream stream)
470 if (stream is IntPtrStream)
471 return new IntPtrStream (stream);
474 if (stream is MemoryStream) {
475 MemoryStream other = (MemoryStream) stream;
476 return new MemoryStream (other.GetBuffer (), 0, (int) other.Length, false, true);
479 if (stream is TempFileStream) {
480 ((TempFileStream) stream).SavePosition ();
484 throw new NotSupportedException ("The stream is " + stream.GetType ());
487 static void EndSubStream (Stream stream)
489 if (stream is TempFileStream) {
490 ((TempFileStream) stream).RestorePosition ();
495 // Loads the data on the form for multipart/form-data
497 void LoadMultiPart ()
499 string boundary = GetParameter (ContentType, "; boundary=");
500 if (boundary == null)
503 Stream input = GetSubStream (InputStream);
504 HttpMultipart multi_part = new HttpMultipart (input, boundary, ContentEncoding);
506 HttpMultipart.Element e;
507 while ((e = multi_part.ReadNextElement ()) != null) {
508 if (e.Filename == null){
509 byte [] copy = new byte [e.Length];
511 input.Position = e.Start;
512 input.Read (copy, 0, (int) e.Length);
514 form.Add (e.Name, ContentEncoding.GetString (copy));
517 // We use a substream, as in 2.x we will support large uploads streamed to disk,
519 HttpPostedFile sub = new HttpPostedFile (e.Filename, e.ContentType, input, e.Start, e.Length);
520 files.AddFile (e.Name, sub);
523 EndSubStream (input);
527 // Adds the key/value to the form, and sets the argumets to empty
529 void AddRawKeyValue (StringBuilder key, StringBuilder value)
531 string decodedKey = HttpUtility.UrlDecode (key.ToString (), ContentEncoding);
532 form.Add (decodedKey,
533 HttpUtility.UrlDecode (value.ToString (), ContentEncoding));
540 // Loads the form data from on a application/x-www-form-urlencoded post
543 void RawLoadWwwForm ()
548 Stream input = GetSubStream (InputStream);
549 StreamReader s = new StreamReader (input, ContentEncoding);
551 StringBuilder key = new StringBuilder ();
552 StringBuilder value = new StringBuilder ();
555 while ((c = s.Read ()) != -1){
558 while ((c = s.Read ()) != -1){
560 AddRawKeyValue (key, value);
563 value.Append ((char) c);
566 AddRawKeyValue (key, value);
570 AddRawKeyValue (key, value);
572 key.Append ((char) c);
575 AddRawKeyValue (key, value);
577 EndSubStream (input);
580 bool IsContentType (string ct, bool starts_with)
583 return StrUtils.StartsWith (ContentType, ct, true);
585 return String.Compare (ContentType, ct, true, CultureInfo.InvariantCulture) == 0;
588 public NameValueCollection Form {
591 form = new WebROCollection ();
592 files = new HttpFileCollection ();
594 if (IsContentType ("multipart/form-data", true))
598 Context.IsPortletRequest ||
600 IsContentType ("application/x-www-form-urlencoded", true))
606 if (validate_form && !checked_form){
607 ValidateNameValueCollection ("Form", form);
615 public NameValueCollection Headers {
618 headers = new HeadersCollection (this);
624 public string HttpMethod {
626 if (http_method == null){
627 if (worker_request != null)
628 http_method = worker_request.GetHttpVerbName ();
636 void DoFilter (byte [] buffer)
638 if (input_filter == null || filter == null)
641 if (buffer.Length < 1024)
642 buffer = new byte [1024];
644 // Replace the input with the filtered input
645 input_filter.BaseStream = input_stream;
646 MemoryStream ms = new MemoryStream ();
648 int n = filter.Read (buffer, 0, buffer.Length);
651 ms.Write (buffer, 0, n);
653 // From now on input_stream has the filtered input
654 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
658 const int INPUT_BUFFER_SIZE = 32*1024;
660 TempFileStream GetTempStream ()
662 string tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
663 TempFileStream f = null;
665 Random rnd = new Random ();
670 path = System.IO.Path.Combine (tempdir, "tmp" + num.ToString("x") + ".req");
673 f = new TempFileStream (path);
674 } catch (SecurityException) {
675 // avoid an endless loop
683 void MakeInputStream ()
685 if (input_stream != null)
688 if (worker_request == null) {
689 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
690 DoFilter (new byte [1024]);
695 // Use an unmanaged memory block as this might be a large
698 int content_length = ContentLength;
701 HttpRuntimeSection config = (HttpRuntimeSection) WebConfigurationManager.GetSection ("system.web/httpRuntime");
703 HttpRuntimeConfig config = (HttpRuntimeConfig) HttpContext.GetAppConfig ("system.web/httpRuntime");
705 if ((content_length / 1024) > config.MaxRequestLength)
706 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
710 buffer = worker_request.GetPreloadedEntityBody ();
711 // we check the instance field 'content_length' here, not the local var.
712 if (this.content_length <= 0 || worker_request.IsEntireEntityBodyIsPreloaded ()) {
713 if (buffer == null || content_length == 0) {
714 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
716 input_stream = new MemoryStream (buffer, 0, buffer.Length, false, true);
718 DoFilter (new byte [1024]);
723 total = buffer.Length;
725 if (content_length > 0 && (content_length / 1024) >= config.RequestLengthDiskThreshold) {
726 // Writes the request to disk
727 total = Math.Min (content_length, total);
728 request_file = GetTempStream ();
729 Stream output = request_file;
731 output.Write (buffer, 0, total);
733 if (total < content_length) {
734 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
737 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
738 n = worker_request.ReadEntityBody (buffer, min);
741 output.Write (buffer, 0, n);
743 } while (total < content_length);
746 request_file.SetReadOnly ();
747 input_stream = request_file;
748 } else if (content_length > 0) {
749 // Buffers the request in an IntPtrStream
750 total = Math.Min (content_length, total);
751 IntPtr content = Marshal.AllocHGlobal (content_length);
752 if (content == (IntPtr) 0)
753 throw new HttpException (String.Format ("Not enough memory to allocate {0} bytes.",
757 Marshal.Copy (buffer, 0, content, total);
759 if (total < content_length) {
760 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
763 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
764 n = worker_request.ReadEntityBody (buffer, min);
767 Marshal.Copy (buffer, 0, (IntPtr) ((long)content + total), n);
769 } while (total < content_length);
772 input_stream = new IntPtrStream (content, total);
774 // Buffers the request in a MemoryStream or writes to disk if threshold exceeded
775 MemoryStream ms = new MemoryStream ();
778 ms.Write (buffer, 0, total);
780 buffer = new byte [INPUT_BUFFER_SIZE];
781 long maxlength = config.MaxRequestLength * 1024;
782 long disk_th = config.RequestLengthDiskThreshold * 1024;
785 n = worker_request.ReadEntityBody (buffer, INPUT_BUFFER_SIZE);
789 if (total < 0 || total > maxlength)
790 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
792 if (ms != null && total > disk_th) {
793 // Swith to on-disk file.
794 request_file = GetTempStream ();
795 ms.WriteTo (request_file);
797 output = request_file;
799 output.Write (buffer, 0, n);
803 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
805 request_file.SetReadOnly ();
806 input_stream = request_file;
811 if (total < content_length)
812 throw new HttpException (411, "The request body is incomplete.");
816 internal void ReleaseResources ()
819 if (input_stream != null){
820 stream = input_stream;
827 if (request_file != null) {
828 stream = request_file;
836 public Stream InputStream {
838 if (input_stream == null)
845 public bool IsAuthenticated {
847 if (context.User == null || context.User.Identity == null)
849 return context.User.Identity.IsAuthenticated;
853 public bool IsSecureConnection {
855 if (worker_request == null)
857 return worker_request.IsSecure ();
861 public string this [string key] {
862 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
864 // "The QueryString, Form, Cookies, or ServerVariables collection member
865 // specified in the key parameter."
866 string val = QueryString [key];
870 HttpCookie cookie = Cookies [key];
875 val = ServerVariables [key];
881 public NameValueCollection Params {
882 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
884 if (all_params == null)
885 all_params = new HttpParamsCollection (QueryString, Form, ServerVariables, Cookies);
893 if (unescaped_path == null) {
895 if (url_components != null) {
896 // use only if it's already been instantiated, so that we can't go into endless
897 // recursion in some scenarios
898 path = UrlComponents.Path;
901 path = ApplyUrlMapping (worker_request.GetUriPath ());
903 path = worker_request.GetUriPath ();
908 unescaped_path = Uri.UnescapeDataString (path);
910 unescaped_path = HttpUtility.UrlDecode (path);
914 return unescaped_path;
918 public string PathInfo {
920 if (path_info == null) {
921 if (worker_request == null)
923 path_info = worker_request.GetPathInfo ();
930 public string PhysicalApplicationPath {
932 if (worker_request == null)
933 throw new ArgumentNullException (); // like 2.0, 1.x throws TypeInitializationException
935 string path = HttpRuntime.AppDomainAppPath;
936 if (SecurityManager.SecurityEnabled) {
937 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
943 public string PhysicalPath {
945 if (worker_request == null)
946 return String.Empty; // don't check security with an empty string!
948 if (physical_path == null) {
949 // Don't call HttpRequest.MapPath here, as that one *trims* the input
950 physical_path = worker_request.MapPath (FilePath);
953 if (SecurityManager.SecurityEnabled) {
954 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, physical_path).Demand ();
956 return physical_path;
960 internal string RootVirtualDir {
962 if (root_virtual_dir == null){
963 string fp = FilePath;
964 int p = fp.LastIndexOf ('/');
967 root_virtual_dir = "/";
969 root_virtual_dir = fp.Substring (0, p);
971 return root_virtual_dir;
975 public NameValueCollection QueryString {
977 if (query_string_nvc == null) {
978 query_string_nvc = new WebROCollection ();
979 string q = UrlComponents.Query;
984 HttpUtility.ParseQueryString (q, ContentEncoding, query_string_nvc);
987 query_string_nvc.Protect();
990 if (validate_query_string && !checked_query_string) {
991 ValidateNameValueCollection ("QueryString", query_string_nvc);
992 checked_query_string = true;
995 return query_string_nvc;
999 public string RawUrl {
1001 if (worker_request != null)
1002 return worker_request.GetRawUrl ();
1004 return UrlComponents.Path + UrlComponents.Query;
1011 public string RequestType {
1013 if (request_type == null){
1014 if (worker_request != null) {
1015 request_type = worker_request.GetHttpVerbName ();
1016 http_method = request_type;
1018 request_type = "GET";
1021 return request_type;
1025 request_type = value;
1029 public NameValueCollection ServerVariables {
1030 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
1032 if (server_variables == null)
1033 server_variables = new ServerVariablesCollection (this);
1035 return server_variables;
1039 public int TotalBytes {
1041 Stream ins = InputStream;
1042 return (int) ins.Length;
1048 if (cached_url == null) {
1049 if (orig_url == null)
1050 cached_url = UrlComponents.Uri;
1052 cached_url = new Uri (orig_url);
1059 public Uri UrlReferrer {
1061 if (worker_request == null)
1064 string hr = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderReferer);
1068 return new Uri (hr);
1072 public string UserAgent {
1074 if (worker_request == null)
1077 return worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderUserAgent);
1081 public string UserHostAddress {
1083 if (worker_request == null)
1086 return worker_request.GetRemoteAddress ();
1090 public string UserHostName {
1092 if (worker_request == null)
1095 return worker_request.GetRemoteName ();
1099 public string [] UserLanguages {
1101 if (worker_request == null)
1104 if (user_languages == null)
1105 user_languages = SplitHeader (HttpWorkerRequest.HeaderAcceptLanguage);
1107 return user_languages;
1111 public byte [] BinaryRead (int count)
1114 throw new ArgumentException ("count is < 0");
1116 Stream s = InputStream;
1117 byte [] ret = new byte [count];
1118 if (s.Read (ret, 0, count) != count)
1119 throw new ArgumentException (
1120 String.Format ("count {0} exceeds length of available input {1}",
1121 count, s.Length - s.Position));
1125 public int [] MapImageCoordinates (string imageFieldName)
1127 string method = HttpMethod;
1128 NameValueCollection coll = null;
1129 if (method == "HEAD" || method == "GET")
1131 else if (method == "POST")
1137 string x = coll [imageFieldName + ".x"];
1138 if (x == null || x == "")
1141 string y = coll [imageFieldName + ".y"];
1142 if (y == null || y == "")
1145 int [] result = new int [2];
1147 result [0] = Int32.Parse (x);
1148 result [1] = Int32.Parse (y);
1156 public string MapPath (string virtualPath)
1158 if (worker_request == null)
1161 return MapPath (virtualPath, BaseVirtualDir, true);
1164 public string MapPath (string virtualPath, string baseVirtualDir, bool allowCrossAppMapping)
1166 if (worker_request == null)
1167 throw new HttpException ("No HttpWorkerRequest");
1169 if (virtualPath == null)
1172 virtualPath = virtualPath.Trim ();
1173 if (virtualPath.Length == 0)
1177 if (virtualPath.IndexOf (':') != -1)
1178 throw new HttpException (String.Format ("'{0}' is not a valid virtual path.", virtualPath));
1180 string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
1182 if (!VirtualPathUtility.IsRooted (virtualPath)) {
1183 if (StrUtils.IsNullOrEmpty (baseVirtualDir))
1184 baseVirtualDir = appVirtualPath;
1185 virtualPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (baseVirtualDir), virtualPath);
1187 virtualPath = VirtualPathUtility.ToAbsolute (virtualPath);
1189 if (!allowCrossAppMapping){
1190 if (!StrUtils.StartsWith (virtualPath, appVirtualPath, true))
1191 throw new HttpException ("MapPath: Mapping across applications not allowed");
1192 if (appVirtualPath.Length > 1 && virtualPath.Length > 1 && virtualPath [0] != '/')
1193 throw new HttpException ("MapPath: Mapping across applications not allowed");
1196 return worker_request.MapPath (virtualPath);
1198 string path = worker_request.MapPath (virtualPath);
1199 if (virtualPath [virtualPath.Length - 1] != '/' && path [path.Length - 1] == System.IO.Path.DirectorySeparatorChar)
1200 path = path.TrimEnd (System.IO.Path.DirectorySeparatorChar);
1205 public void SaveAs (string filename, bool includeHeaders)
1207 Stream output = new FileStream (filename, FileMode.Create);
1208 if (includeHeaders) {
1209 StringBuilder sb = new StringBuilder ();
1210 string version = String.Empty;
1212 if (worker_request != null) {
1213 version = worker_request.GetHttpVersion ();
1214 path = UrlComponents.Path;
1216 string qs = UrlComponents.Query;
1218 sb.AppendFormat ("{0} {1}{2} {3}\r\n", HttpMethod, path, qs, version);
1219 NameValueCollection coll = Headers;
1220 foreach (string k in coll.AllKeys) {
1223 sb.Append (coll [k]);
1228 byte [] bytes = Encoding.GetEncoding (28591).GetBytes (sb.ToString ());
1229 output.Write (bytes, 0, bytes.Length);
1232 // More than 1 call to SaveAs works fine on MS, so we "copy" the stream
1233 // to keep InputStream in its state.
1234 Stream input = GetSubStream (InputStream);
1236 long len = input.Length;
1237 int buf_size = (int) Math.Min ((len < 0 ? 0 : len), 8192);
1238 byte [] data = new byte [buf_size];
1240 while (len > 0 && (count = input.Read (data, 0, buf_size)) > 0) {
1241 output.Write (data, 0, count);
1247 EndSubStream (input);
1251 public void ValidateInput ()
1253 validate_cookies = true;
1254 validate_query_string = true;
1255 validate_form = true;
1258 #region internal routines
1259 internal string ClientTarget {
1261 return client_target;
1265 client_target = value;
1276 string address = worker_request.GetRemoteAddress ();
1278 if (StrUtils.IsNullOrEmpty (address))
1281 if (address == "127.0.0.1")
1284 System.Net.IPAddress remoteAddr = System.Net.IPAddress.Parse (address);
1285 if (System.Net.IPAddress.IsLoopback (remoteAddr))
1288 for (int i = 0; i < host_addresses.Length; i++)
1289 if (remoteAddr.Equals (host_addresses [i]))
1296 internal void SetFilePath (string path)
1299 physical_path = null;
1302 internal void SetCurrentExePath (string path)
1305 current_exe_path = path;
1307 UrlComponents.Path = path;
1308 // recreated on demand
1309 root_virtual_dir = null;
1310 base_virtual_dir = null;
1311 physical_path = null;
1312 unescaped_path = null;
1315 internal void SetPathInfo (string pi)
1321 // Headers is ReadOnly, so we need this hack for cookie-less sessions.
1322 internal void SetHeader (string name, string value)
1324 WebROCollection h = (WebROCollection) Headers;
1330 // Notice: there is nothing raw about this querystring.
1331 internal string QueryStringRaw {
1333 return UrlComponents.Query;
1337 UrlComponents.Query = value;
1339 query_string_nvc = null;
1343 // Internal, dont know what it does, so flagged as public so we can see it.
1344 internal void SetForm (WebROCollection coll)
1349 internal HttpWorkerRequest WorkerRequest {
1351 return worker_request;
1355 internal HttpContext Context {
1361 static void ValidateNameValueCollection (string name, NameValueCollection coll)
1366 foreach (string key in coll.Keys) {
1367 string val = coll [key];
1368 if (val != null && val != "" && CheckString (val))
1369 ThrowValidationException (name, key, val);
1373 static void ValidateCookieCollection (HttpCookieCollection cookies)
1375 if (cookies == null)
1378 int size = cookies.Count;
1380 for (int i = 0 ; i < size ; i++) {
1381 cookie = cookies[i];
1382 string value = cookie.Value;
1384 if (value != null && value != "" && CheckString (value))
1385 ThrowValidationException ("Cookies", cookie.Name, cookie.Value);
1389 static void ThrowValidationException (string name, string key, string value)
1391 string v = "\"" + value + "\"";
1393 v = v.Substring (0, 16) + "...\"";
1395 string msg = String.Format ("A potentially dangerous Request.{0} value was " +
1396 "detected from the client ({1}={2}).", name, key, v);
1398 throw new HttpRequestValidationException (msg);
1401 static bool CheckString (string val)
1403 int len = val.Length;
1407 char current = val [0];
1408 for (int idx = 1; idx < len; idx++) {
1409 char next = val [idx];
1410 if (current == '<' || current == '\xff1c') {
1411 if (next == '!' || next < ' '
1412 || (next >= 'a' && next <= 'z')
1413 || (next >= 'A' && next <= 'Z'))
1415 } else if (current == '&' && next == '#') {
1425 static System.Net.IPAddress [] GetLocalHostAddresses ()
1428 string hostName = System.Net.Dns.GetHostName ();
1430 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostAddresses (hostName);
1432 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostByName (hostName).AddressList;
1438 return new System.Net.IPAddress[0];
1444 #region Helper classes
1447 // Stream-based multipart handling.
1449 // In this incarnation deals with an HttpInputStream as we are now using
1450 // IntPtr-based streams instead of byte []. In the future, we will also
1451 // send uploads above a certain threshold into the disk (to implement
1452 // limit-less HttpInputFiles).
1455 class HttpMultipart {
1457 public class Element {
1458 public string ContentType;
1460 public string Filename;
1464 public override string ToString ()
1466 return string.Format ("ContentType {0}, Name {1}, Filename {2}, Start {3}, Length {4}",
1467 ContentType, Name, Filename, Start, Length);
1473 byte [] boundary_bytes;
1479 const byte HYPHEN = (byte) '-', LF = (byte) '\n', CR = (byte) '\r';
1482 // In the case of multipart entities, in which one or more different
1483 // sets of data are combined in a single body, a "multipart" media type
1484 // field must appear in the entity's header. The body must then contain
1485 // one or more body parts, each preceded by a boundary delimiter line,
1486 // and the last one followed by a closing boundary delimiter line.
1487 // After its boundary delimiter line, each body part then consists of a
1488 // header area, a blank line, and a body area. Thus a body part is
1489 // similar to an RFC 822 message in syntax, but different in meaning.
1491 public HttpMultipart (Stream data, string b, Encoding encoding)
1495 boundary_bytes = encoding.GetBytes (b);
1496 buffer = new byte [boundary_bytes.Length + 2]; // CRLF or '--'
1497 this.encoding = encoding;
1498 sb = new StringBuilder ();
1503 // CRLF or LF are ok as line endings.
1504 bool got_cr = false;
1508 b = data.ReadByte ();
1517 sb.Append ((char) b);
1523 return sb.ToString ();
1527 static string GetContentDispositionAttribute (string l, string name)
1529 int idx = l.IndexOf (name + "=\"");
1532 int begin = idx + name.Length + "=\"".Length;
1533 int end = l.IndexOf ('"', begin);
1538 return l.Substring (begin, end - begin);
1541 string GetContentDispositionAttributeWithEncoding (string l, string name)
1543 int idx = l.IndexOf (name + "=\"");
1546 int begin = idx + name.Length + "=\"".Length;
1547 int end = l.IndexOf ('"', begin);
1553 string temp = l.Substring (begin, end - begin);
1554 byte [] source = new byte [temp.Length];
1555 for (int i = temp.Length - 1; i >= 0; i--)
1556 source [i] = (byte) temp [i];
1558 return encoding.GetString (source);
1561 bool ReadBoundary ()
1564 string line = ReadLine ();
1567 if (line [0] != '-' || line [1] != '-')
1570 if (!StrUtils.EndsWith (line, boundary, false))
1578 string ReadHeaders ()
1580 string s = ReadLine ();
1587 bool CompareBytes (byte [] orig, byte [] other)
1589 for (int i = orig.Length - 1; i >= 0; i--)
1590 if (orig [i] != other [i])
1596 long MoveToNextBoundary ()
1599 bool got_cr = false;
1602 int c = data.ReadByte ();
1607 if (state == 0 && c == LF) {
1608 retval = data.Position - 1;
1612 c = data.ReadByte ();
1613 } else if (state == 0) {
1615 c = data.ReadByte ();
1616 } else if (state == 1 && c == '-') {
1617 c = data.ReadByte ();
1624 continue; // no ReadByte() here
1627 int nread = data.Read (buffer, 0, buffer.Length);
1628 int bl = buffer.Length;
1632 if (!CompareBytes (boundary_bytes, buffer)) {
1634 data.Position = retval + 2;
1639 c = data.ReadByte ();
1643 if (buffer [bl - 2] == '-' && buffer [bl - 1] == '-') {
1645 } else if (buffer [bl - 2] != CR || buffer [bl - 1] != LF) {
1647 data.Position = retval + 2;
1652 c = data.ReadByte ();
1655 data.Position = retval + 2;
1661 state = 0; // no ReadByte() here
1668 public Element ReadNextElement ()
1670 if (at_eof || ReadBoundary ())
1673 Element elem = new Element ();
1675 while ((header = ReadHeaders ()) != null) {
1676 if (StrUtils.StartsWith (header, "Content-Disposition:", true)) {
1677 elem.Name = GetContentDispositionAttribute (header, "name");
1678 elem.Filename = StripPath (GetContentDispositionAttributeWithEncoding (header, "filename"));
1679 } else if (StrUtils.StartsWith (header, "Content-Type:", true)) {
1680 elem.ContentType = header.Substring ("Content-Type:".Length).Trim ();
1684 long start = data.Position;
1686 long pos = MoveToNextBoundary ();
1690 elem.Length = pos - start;
1694 static string StripPath (string path)
1696 if (path == null || path.Length == 0)
1699 if (path.IndexOf (":\\") != 1)
1701 return path.Substring (path.LastIndexOf ("\\") + 1);