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 HttpUtility.ParseQueryString (queryString, Encoding.Default, query_string_nvc);
117 query_string_nvc.Protect ();
120 internal HttpRequest (HttpWorkerRequest worker_request, HttpContext context)
122 this.worker_request = worker_request;
123 this.context = context;
126 UriBuilder UrlComponents {
128 if (url_components == null) {
130 byte[] queryStringRaw = worker_request.GetQueryStringRawBytes();
131 if(queryStringRaw != null)
132 query = ContentEncoding.GetString(queryStringRaw);
134 query = worker_request.GetQueryString();
138 ApplyUrlMapping (worker_request.GetUriPath ()),
140 worker_request.GetUriPath (),
144 return url_components;
148 void BuildUrlComponents (string path, string query)
150 if (url_components != null)
152 url_components = new UriBuilder ();
153 url_components.Scheme = worker_request.GetProtocol ();
154 url_components.Host = worker_request.GetServerName ();
155 url_components.Port = worker_request.GetLocalPort ();
156 url_components.Path = path;
157 if (query != null && query.Length > 0)
158 url_components.Query = query.TrimStart (queryTrimChars);
162 internal string ApplyUrlMapping (string url)
164 if (WebConfigurationManager.HasConfigErrors)
167 UrlMappingsSection ums = WebConfigurationManager.GetSection ("system.web/urlMappings", ApplicationPath) as UrlMappingsSection;
168 UrlMappingCollection umc;
170 if (ums == null || !ums.IsEnabled || (umc = ums.UrlMappings).Count == 0)
173 string relUrl = VirtualPathUtility.ToAppRelative (url);
174 UrlMapping um = null;
176 foreach (UrlMapping u in umc) {
179 if (String.Compare (relUrl, u.Url, StringComparison.Ordinal) == 0) {
188 string rawUrl = VirtualPathUtility.ToAbsolute (um.MappedUrl.Trim ());
189 Uri newUrl = new Uri ("http://host.com" + rawUrl);
191 if (url_components != null) {
192 url_components.Path = newUrl.AbsolutePath;
193 url_components.Query = newUrl.Query.TrimStart (queryTrimChars);
194 query_string_nvc = new WebROCollection ();
195 HttpUtility.ParseQueryString (newUrl.Query, Encoding.Default, query_string_nvc);
196 query_string_nvc.Protect ();
198 BuildUrlComponents (newUrl.AbsolutePath, newUrl.Query);
200 return url_components.Path;
204 string [] SplitHeader (int header_index)
206 string [] result = null;
207 string header = worker_request.GetKnownRequestHeader (header_index);
208 if (header != null && header != "" && header.Trim () != "") {
209 result = header.Split (',');
210 for (int i = result.Length - 1; i >= 0; i--)
211 result [i] = result [i].Trim ();
216 public string [] AcceptTypes {
218 if (worker_request == null)
221 if (accept_types == null)
222 accept_types = SplitHeader (HttpWorkerRequest.HeaderAccept);
230 public string AnonymousID {
235 anonymous_id = value;
240 public string ApplicationPath {
242 if (worker_request == null)
244 return worker_request.GetAppPath ();
248 public HttpBrowserCapabilities Browser {
250 if (browser_capabilities == null)
251 browser_capabilities = (HttpBrowserCapabilities)
252 HttpCapabilitiesBase.GetConfigCapabilities (null, this);
254 return browser_capabilities;
258 browser_capabilities = value;
262 public HttpClientCertificate ClientCertificate {
264 if (client_cert == null)
265 client_cert = new HttpClientCertificate (worker_request);
270 static internal string GetParameter (string header, string attr)
272 int ap = header.IndexOf (attr);
277 if (ap >= header.Length)
280 char ending = header [ap];
284 int end = header.IndexOf (ending, ap+1);
286 return (ending == '"') ? null : header.Substring (ap);
288 return header.Substring (ap+1, end-ap-1);
291 public Encoding ContentEncoding {
293 if (encoding == null){
294 if (worker_request == null)
295 throw new HttpException ("No HttpWorkerRequest");
297 string content_type = ContentType;
298 string parameter = GetParameter (content_type, "; charset=");
299 if (parameter == null) {
300 encoding = WebEncoding.RequestEncoding;
303 // Do what the #1 web server does
304 encoding = Encoding.GetEncoding (parameter);
306 encoding = WebEncoding.RequestEncoding;
318 public int ContentLength {
320 if (content_length == -1){
321 if (worker_request == null)
324 string cl = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentLength);
328 content_length = Int32.Parse (cl);
333 // content_length will still be < 0, but we know we gotta read from the client
334 if (content_length < 0)
337 return content_length;
341 public string ContentType {
343 if (content_type == null){
344 if (worker_request != null)
345 content_type = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentType);
347 if (content_type == null)
348 content_type = String.Empty;
355 content_type = value;
359 public HttpCookieCollection Cookies {
361 if (cookies == null) {
362 if (worker_request == null) {
363 cookies = new HttpCookieCollection ();
365 string cookie_hv = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderCookie);
366 cookies = new HttpCookieCollection (cookie_hv);
371 // For J2EE portal support we emulate cookies using the session.
372 GetSessionCookiesForPortal (cookies);
374 if (validate_cookies && !checked_cookies){
375 ValidateCookieCollection (cookies);
376 checked_cookies = true;
384 public string CurrentExecutionFilePath {
386 if (current_exe_path != null)
387 return current_exe_path;
394 public string AppRelativeCurrentExecutionFilePath {
396 return VirtualPathUtility.ToAppRelative (CurrentExecutionFilePath);
401 public string FilePath {
403 if (worker_request == null)
404 return "/"; // required for 2.0
406 if (file_path == null)
407 file_path = UrlUtils.Canonic (
409 ApplyUrlMapping (worker_request.GetFilePath ())
411 worker_request.GetFilePath ()
419 internal string BaseVirtualDir {
421 if (base_virtual_dir == null){
422 base_virtual_dir = FilePath;
423 int p = base_virtual_dir.LastIndexOf ('/');
425 base_virtual_dir = base_virtual_dir.Substring (0, p);
427 return base_virtual_dir;
431 public HttpFileCollection Files {
434 files = new HttpFileCollection ();
435 if ((worker_request != null) && IsContentType ("multipart/form-data", true)) {
436 form = new WebROCollection ();
445 public Stream Filter {
450 if (input_filter == null)
451 input_filter = new InputFilterStream ();
457 // This checks that get_ was called before.
458 if (input_filter == null)
459 throw new HttpException ("Invalid filter");
465 // GetSubStream returns a 'copy' of the InputStream with Position set to 0.
466 static Stream GetSubStream (Stream stream)
469 if (stream is IntPtrStream)
470 return new IntPtrStream (stream);
473 if (stream is MemoryStream) {
474 MemoryStream other = (MemoryStream) stream;
475 return new MemoryStream (other.GetBuffer (), 0, (int) other.Length, false, true);
478 if (stream is TempFileStream) {
479 ((TempFileStream) stream).SavePosition ();
483 throw new NotSupportedException ("The stream is " + stream.GetType ());
486 static void EndSubStream (Stream stream)
488 if (stream is TempFileStream) {
489 ((TempFileStream) stream).RestorePosition ();
494 // Loads the data on the form for multipart/form-data
496 void LoadMultiPart ()
498 string boundary = GetParameter (ContentType, "; boundary=");
499 if (boundary == null)
502 Stream input = GetSubStream (InputStream);
503 HttpMultipart multi_part = new HttpMultipart (input, boundary, ContentEncoding);
505 HttpMultipart.Element e;
506 while ((e = multi_part.ReadNextElement ()) != null) {
507 if (e.Filename == null){
508 byte [] copy = new byte [e.Length];
510 input.Position = e.Start;
511 input.Read (copy, 0, (int) e.Length);
513 form.Add (e.Name, ContentEncoding.GetString (copy));
516 // We use a substream, as in 2.x we will support large uploads streamed to disk,
518 HttpPostedFile sub = new HttpPostedFile (e.Filename, e.ContentType, input, e.Start, e.Length);
519 files.AddFile (e.Name, sub);
522 EndSubStream (input);
526 // Adds the key/value to the form, and sets the argumets to empty
528 void AddRawKeyValue (StringBuilder key, StringBuilder value)
530 string decodedKey = HttpUtility.UrlDecode (key.ToString (), ContentEncoding);
531 form.Add (decodedKey,
532 HttpUtility.UrlDecode (value.ToString (), ContentEncoding));
539 // Loads the form data from on a application/x-www-form-urlencoded post
542 void RawLoadWwwForm ()
547 Stream input = GetSubStream (InputStream);
548 StreamReader s = new StreamReader (input, ContentEncoding);
550 StringBuilder key = new StringBuilder ();
551 StringBuilder value = new StringBuilder ();
554 while ((c = s.Read ()) != -1){
557 while ((c = s.Read ()) != -1){
559 AddRawKeyValue (key, value);
562 value.Append ((char) c);
565 AddRawKeyValue (key, value);
569 AddRawKeyValue (key, value);
571 key.Append ((char) c);
574 AddRawKeyValue (key, value);
576 EndSubStream (input);
579 bool IsContentType (string ct, bool starts_with)
582 return StrUtils.StartsWith (ContentType, ct, true);
584 return String.Compare (ContentType, ct, true, CultureInfo.InvariantCulture) == 0;
587 public NameValueCollection Form {
590 form = new WebROCollection ();
591 files = new HttpFileCollection ();
593 if (IsContentType ("multipart/form-data", true))
597 Context.IsPortletRequest ||
599 IsContentType ("application/x-www-form-urlencoded", true))
605 if (validate_form && !checked_form){
606 ValidateNameValueCollection ("Form", form);
614 public NameValueCollection Headers {
617 headers = new HeadersCollection (this);
623 public string HttpMethod {
625 if (http_method == null){
626 if (worker_request != null)
627 http_method = worker_request.GetHttpVerbName ();
635 void DoFilter (byte [] buffer)
637 if (input_filter == null || filter == null)
640 if (buffer.Length < 1024)
641 buffer = new byte [1024];
643 // Replace the input with the filtered input
644 input_filter.BaseStream = input_stream;
645 MemoryStream ms = new MemoryStream ();
647 int n = filter.Read (buffer, 0, buffer.Length);
650 ms.Write (buffer, 0, n);
652 // From now on input_stream has the filtered input
653 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
657 const int INPUT_BUFFER_SIZE = 32*1024;
659 TempFileStream GetTempStream ()
661 string tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
662 TempFileStream f = null;
664 Random rnd = new Random ();
669 path = System.IO.Path.Combine (tempdir, "tmp" + num.ToString("x") + ".req");
672 f = new TempFileStream (path);
673 } catch (SecurityException) {
674 // avoid an endless loop
682 void MakeInputStream ()
684 if (input_stream != null)
687 if (worker_request == null) {
688 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
689 DoFilter (new byte [1024]);
694 // Use an unmanaged memory block as this might be a large
697 int content_length = ContentLength;
700 HttpRuntimeSection config = (HttpRuntimeSection) WebConfigurationManager.GetSection ("system.web/httpRuntime");
702 HttpRuntimeConfig config = (HttpRuntimeConfig) HttpContext.GetAppConfig ("system.web/httpRuntime");
704 if ((content_length / 1024) > config.MaxRequestLength)
705 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
709 buffer = worker_request.GetPreloadedEntityBody ();
710 // we check the instance field 'content_length' here, not the local var.
711 if (this.content_length <= 0 || worker_request.IsEntireEntityBodyIsPreloaded ()) {
712 if (buffer == null || content_length == 0) {
713 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
715 input_stream = new MemoryStream (buffer, 0, buffer.Length, false, true);
717 DoFilter (new byte [1024]);
722 total = buffer.Length;
724 if (content_length > 0 && (content_length / 1024) >= config.RequestLengthDiskThreshold) {
725 // Writes the request to disk
726 total = Math.Min (content_length, total);
727 request_file = GetTempStream ();
728 Stream output = request_file;
730 output.Write (buffer, 0, total);
732 if (total < content_length) {
733 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
736 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
737 n = worker_request.ReadEntityBody (buffer, min);
740 output.Write (buffer, 0, n);
742 } while (total < content_length);
745 request_file.SetReadOnly ();
746 input_stream = request_file;
747 } else if (content_length > 0) {
748 // Buffers the request in an IntPtrStream
749 total = Math.Min (content_length, total);
750 IntPtr content = Marshal.AllocHGlobal (content_length);
751 if (content == (IntPtr) 0)
752 throw new HttpException (String.Format ("Not enough memory to allocate {0} bytes.",
756 Marshal.Copy (buffer, 0, content, total);
758 if (total < content_length) {
759 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
762 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
763 n = worker_request.ReadEntityBody (buffer, min);
766 Marshal.Copy (buffer, 0, (IntPtr) ((long)content + total), n);
768 } while (total < content_length);
771 input_stream = new IntPtrStream (content, total);
773 // Buffers the request in a MemoryStream or writes to disk if threshold exceeded
774 MemoryStream ms = new MemoryStream ();
777 ms.Write (buffer, 0, total);
779 buffer = new byte [INPUT_BUFFER_SIZE];
780 long maxlength = config.MaxRequestLength * 1024;
781 long disk_th = config.RequestLengthDiskThreshold * 1024;
784 n = worker_request.ReadEntityBody (buffer, INPUT_BUFFER_SIZE);
788 if (total < 0 || total > maxlength)
789 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
791 if (ms != null && total > disk_th) {
792 // Swith to on-disk file.
793 request_file = GetTempStream ();
794 ms.WriteTo (request_file);
796 output = request_file;
798 output.Write (buffer, 0, n);
802 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
804 request_file.SetReadOnly ();
805 input_stream = request_file;
810 if (total < content_length)
811 throw new HttpException (411, "The request body is incomplete.");
815 internal void ReleaseResources ()
818 if (input_stream != null){
819 stream = input_stream;
826 if (request_file != null) {
827 stream = request_file;
835 public Stream InputStream {
837 if (input_stream == null)
844 public bool IsAuthenticated {
846 if (context.User == null || context.User.Identity == null)
848 return context.User.Identity.IsAuthenticated;
852 public bool IsSecureConnection {
854 if (worker_request == null)
856 return worker_request.IsSecure ();
860 public string this [string key] {
861 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
863 // "The QueryString, Form, Cookies, or ServerVariables collection member
864 // specified in the key parameter."
865 string val = QueryString [key];
869 HttpCookie cookie = Cookies [key];
874 val = ServerVariables [key];
880 public NameValueCollection Params {
881 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
883 if (all_params == null)
884 all_params = new HttpParamsCollection (QueryString, Form, ServerVariables, Cookies);
892 if (unescaped_path == null) {
894 if (url_components != null) {
895 // use only if it's already been instantiated, so that we can't go into endless
896 // recursion in some scenarios
897 path = UrlComponents.Path;
900 path = ApplyUrlMapping (worker_request.GetUriPath ());
902 path = worker_request.GetUriPath ();
907 unescaped_path = Uri.UnescapeDataString (path);
909 unescaped_path = HttpUtility.UrlDecode (path);
913 return unescaped_path;
917 public string PathInfo {
919 if (path_info == null) {
920 if (worker_request == null)
922 path_info = worker_request.GetPathInfo ();
929 public string PhysicalApplicationPath {
931 if (worker_request == null)
932 throw new ArgumentNullException (); // like 2.0, 1.x throws TypeInitializationException
934 string path = HttpRuntime.AppDomainAppPath;
935 if (SecurityManager.SecurityEnabled) {
936 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
942 public string PhysicalPath {
944 if (worker_request == null)
945 return String.Empty; // don't check security with an empty string!
947 if (physical_path == null) {
948 // Don't call HttpRequest.MapPath here, as that one *trims* the input
949 physical_path = worker_request.MapPath (FilePath);
952 if (SecurityManager.SecurityEnabled) {
953 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, physical_path).Demand ();
955 return physical_path;
959 internal string RootVirtualDir {
961 if (root_virtual_dir == null){
962 string fp = FilePath;
963 int p = fp.LastIndexOf ('/');
966 root_virtual_dir = "/";
968 root_virtual_dir = fp.Substring (0, p);
970 return root_virtual_dir;
974 public NameValueCollection QueryString {
976 if (query_string_nvc == null){
977 string q = UrlComponents.Query;
981 query_string_nvc = new WebROCollection ();
982 HttpUtility.ParseQueryString (q, ContentEncoding, query_string_nvc);
983 query_string_nvc.Protect();
986 if (validate_query_string && !checked_query_string) {
987 ValidateNameValueCollection ("QueryString", query_string_nvc);
988 checked_query_string = true;
991 return query_string_nvc;
995 public string RawUrl {
997 if (worker_request != null)
998 return worker_request.GetRawUrl ();
1000 return UrlComponents.Path + UrlComponents.Query;
1007 public string RequestType {
1009 if (request_type == null){
1010 if (worker_request != null) {
1011 request_type = worker_request.GetHttpVerbName ();
1012 http_method = request_type;
1014 request_type = "GET";
1017 return request_type;
1021 request_type = value;
1025 public NameValueCollection ServerVariables {
1026 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
1028 if (server_variables == null)
1029 server_variables = new ServerVariablesCollection (this);
1031 return server_variables;
1035 public int TotalBytes {
1037 Stream ins = InputStream;
1038 return (int) ins.Length;
1044 if (cached_url == null) {
1045 if (orig_url == null)
1046 cached_url = UrlComponents.Uri;
1048 cached_url = new Uri (orig_url);
1055 public Uri UrlReferrer {
1057 if (worker_request == null)
1060 string hr = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderReferer);
1064 return new Uri (hr);
1068 public string UserAgent {
1070 if (worker_request == null)
1073 return worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderUserAgent);
1077 public string UserHostAddress {
1079 if (worker_request == null)
1082 return worker_request.GetRemoteAddress ();
1086 public string UserHostName {
1088 if (worker_request == null)
1091 return worker_request.GetRemoteName ();
1095 public string [] UserLanguages {
1097 if (worker_request == null)
1100 if (user_languages == null)
1101 user_languages = SplitHeader (HttpWorkerRequest.HeaderAcceptLanguage);
1103 return user_languages;
1107 public byte [] BinaryRead (int count)
1110 throw new ArgumentException ("count is < 0");
1112 Stream s = InputStream;
1113 byte [] ret = new byte [count];
1114 if (s.Read (ret, 0, count) != count)
1115 throw new ArgumentException (
1116 String.Format ("count {0} exceeds length of available input {1}",
1117 count, s.Length - s.Position));
1121 public int [] MapImageCoordinates (string imageFieldName)
1123 string method = HttpMethod;
1124 NameValueCollection coll = null;
1125 if (method == "HEAD" || method == "GET")
1127 else if (method == "POST")
1133 string x = coll [imageFieldName + ".x"];
1134 if (x == null || x == "")
1137 string y = coll [imageFieldName + ".y"];
1138 if (y == null || y == "")
1141 int [] result = new int [2];
1143 result [0] = Int32.Parse (x);
1144 result [1] = Int32.Parse (y);
1152 public string MapPath (string virtualPath)
1154 if (worker_request == null)
1157 return MapPath (virtualPath, BaseVirtualDir, true);
1160 public string MapPath (string virtualPath, string baseVirtualDir, bool allowCrossAppMapping)
1162 if (worker_request == null)
1163 throw new HttpException ("No HttpWorkerRequest");
1165 if (virtualPath == null)
1168 virtualPath = virtualPath.Trim ();
1169 if (virtualPath.Length == 0)
1173 if (virtualPath.IndexOf (':') != -1)
1174 throw new HttpException (String.Format ("'{0}' is not a valid virtual path.", virtualPath));
1176 string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
1178 if (!VirtualPathUtility.IsRooted (virtualPath)) {
1179 if (StrUtils.IsNullOrEmpty (baseVirtualDir))
1180 baseVirtualDir = appVirtualPath;
1181 virtualPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (baseVirtualDir), virtualPath);
1183 virtualPath = VirtualPathUtility.ToAbsolute (virtualPath);
1185 if (!allowCrossAppMapping){
1186 if (!StrUtils.StartsWith (virtualPath, appVirtualPath, true))
1187 throw new HttpException ("MapPath: Mapping across applications not allowed");
1188 if (appVirtualPath.Length > 1 && virtualPath.Length > 1 && virtualPath [0] != '/')
1189 throw new HttpException ("MapPath: Mapping across applications not allowed");
1192 return worker_request.MapPath (virtualPath);
1194 string path = worker_request.MapPath (virtualPath);
1195 if (virtualPath [virtualPath.Length - 1] != '/' && path [path.Length - 1] == System.IO.Path.DirectorySeparatorChar)
1196 path = path.TrimEnd (System.IO.Path.DirectorySeparatorChar);
1201 public void SaveAs (string filename, bool includeHeaders)
1203 Stream output = new FileStream (filename, FileMode.Create);
1204 if (includeHeaders) {
1205 StringBuilder sb = new StringBuilder ();
1206 string version = String.Empty;
1208 if (worker_request != null) {
1209 version = worker_request.GetHttpVersion ();
1210 path = UrlComponents.Path;
1212 string qs = UrlComponents.Query;
1214 sb.AppendFormat ("{0} {1}{2} {3}\r\n", HttpMethod, path, qs, version);
1215 NameValueCollection coll = Headers;
1216 foreach (string k in coll.AllKeys) {
1219 sb.Append (coll [k]);
1224 byte [] bytes = Encoding.GetEncoding (28591).GetBytes (sb.ToString ());
1225 output.Write (bytes, 0, bytes.Length);
1228 // More than 1 call to SaveAs works fine on MS, so we "copy" the stream
1229 // to keep InputStream in its state.
1230 Stream input = GetSubStream (InputStream);
1232 long len = input.Length;
1233 int buf_size = (int) Math.Min ((len < 0 ? 0 : len), 8192);
1234 byte [] data = new byte [buf_size];
1236 while (len > 0 && (count = input.Read (data, 0, buf_size)) > 0) {
1237 output.Write (data, 0, count);
1243 EndSubStream (input);
1247 public void ValidateInput ()
1249 validate_cookies = true;
1250 validate_query_string = true;
1251 validate_form = true;
1254 #region internal routines
1255 internal string ClientTarget {
1257 return client_target;
1261 client_target = value;
1272 string address = worker_request.GetRemoteAddress ();
1274 if (StrUtils.IsNullOrEmpty (address))
1277 if (address == "127.0.0.1")
1280 System.Net.IPAddress remoteAddr = System.Net.IPAddress.Parse (address);
1281 if (System.Net.IPAddress.IsLoopback (remoteAddr))
1284 for (int i = 0; i < host_addresses.Length; i++)
1285 if (remoteAddr.Equals (host_addresses [i]))
1292 internal void SetFilePath (string path)
1295 physical_path = null;
1298 internal void SetCurrentExePath (string path)
1301 current_exe_path = path;
1303 UrlComponents.Path = path;
1304 // recreated on demand
1305 root_virtual_dir = null;
1306 base_virtual_dir = null;
1307 physical_path = null;
1308 unescaped_path = null;
1311 internal void SetPathInfo (string pi)
1317 // Headers is ReadOnly, so we need this hack for cookie-less sessions.
1318 internal void SetHeader (string name, string value)
1320 WebROCollection h = (WebROCollection) Headers;
1326 // Notice: there is nothing raw about this querystring.
1327 internal string QueryStringRaw {
1329 return UrlComponents.Query;
1333 UrlComponents.Query = value;
1335 query_string_nvc = null;
1339 // Internal, dont know what it does, so flagged as public so we can see it.
1340 internal void SetForm (WebROCollection coll)
1345 internal HttpWorkerRequest WorkerRequest {
1347 return worker_request;
1351 internal HttpContext Context {
1357 static void ValidateNameValueCollection (string name, NameValueCollection coll)
1362 foreach (string key in coll.Keys) {
1363 string val = coll [key];
1364 if (val != null && val != "" && CheckString (val))
1365 ThrowValidationException (name, key, val);
1369 static void ValidateCookieCollection (HttpCookieCollection cookies)
1371 if (cookies == null)
1374 int size = cookies.Count;
1376 for (int i = 0 ; i < size ; i++) {
1377 cookie = cookies[i];
1378 string value = cookie.Value;
1380 if (value != null && value != "" && CheckString (value))
1381 ThrowValidationException ("Cookies", cookie.Name, cookie.Value);
1385 static void ThrowValidationException (string name, string key, string value)
1387 string v = "\"" + value + "\"";
1389 v = v.Substring (0, 16) + "...\"";
1391 string msg = String.Format ("A potentially dangerous Request.{0} value was " +
1392 "detected from the client ({1}={2}).", name, key, v);
1394 throw new HttpRequestValidationException (msg);
1397 static bool CheckString (string val)
1399 int len = val.Length;
1403 char current = val [0];
1404 for (int idx = 1; idx < len; idx++) {
1405 char next = val [idx];
1406 if (current == '<' || current == '\xff1c') {
1407 if (next == '!' || next < ' '
1408 || (next >= 'a' && next <= 'z')
1409 || (next >= 'A' && next <= 'Z'))
1411 } else if (current == '&' && next == '#') {
1421 static System.Net.IPAddress [] GetLocalHostAddresses ()
1424 string hostName = System.Net.Dns.GetHostName ();
1426 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostAddresses (hostName);
1428 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostByName (hostName).AddressList;
1434 return new System.Net.IPAddress[0];
1440 #region Helper classes
1443 // Stream-based multipart handling.
1445 // In this incarnation deals with an HttpInputStream as we are now using
1446 // IntPtr-based streams instead of byte []. In the future, we will also
1447 // send uploads above a certain threshold into the disk (to implement
1448 // limit-less HttpInputFiles).
1451 class HttpMultipart {
1453 public class Element {
1454 public string ContentType;
1456 public string Filename;
1460 public override string ToString ()
1462 return string.Format ("ContentType {0}, Name {1}, Filename {2}, Start {3}, Length {4}",
1463 ContentType, Name, Filename, Start, Length);
1469 byte [] boundary_bytes;
1475 const byte HYPHEN = (byte) '-', LF = (byte) '\n', CR = (byte) '\r';
1478 // In the case of multipart entities, in which one or more different
1479 // sets of data are combined in a single body, a "multipart" media type
1480 // field must appear in the entity's header. The body must then contain
1481 // one or more body parts, each preceded by a boundary delimiter line,
1482 // and the last one followed by a closing boundary delimiter line.
1483 // After its boundary delimiter line, each body part then consists of a
1484 // header area, a blank line, and a body area. Thus a body part is
1485 // similar to an RFC 822 message in syntax, but different in meaning.
1487 public HttpMultipart (Stream data, string b, Encoding encoding)
1491 boundary_bytes = encoding.GetBytes (b);
1492 buffer = new byte [boundary_bytes.Length + 2]; // CRLF or '--'
1493 this.encoding = encoding;
1494 sb = new StringBuilder ();
1499 // CRLF or LF are ok as line endings.
1500 bool got_cr = false;
1504 b = data.ReadByte ();
1513 sb.Append ((char) b);
1519 return sb.ToString ();
1523 static string GetContentDispositionAttribute (string l, string name)
1525 int idx = l.IndexOf (name + "=\"");
1528 int begin = idx + name.Length + "=\"".Length;
1529 int end = l.IndexOf ('"', begin);
1534 return l.Substring (begin, end - begin);
1537 string GetContentDispositionAttributeWithEncoding (string l, string name)
1539 int idx = l.IndexOf (name + "=\"");
1542 int begin = idx + name.Length + "=\"".Length;
1543 int end = l.IndexOf ('"', begin);
1549 string temp = l.Substring (begin, end - begin);
1550 byte [] source = new byte [temp.Length];
1551 for (int i = temp.Length - 1; i >= 0; i--)
1552 source [i] = (byte) temp [i];
1554 return encoding.GetString (source);
1557 bool ReadBoundary ()
1560 string line = ReadLine ();
1563 if (line [0] != '-' || line [1] != '-')
1566 if (!StrUtils.EndsWith (line, boundary, false))
1574 string ReadHeaders ()
1576 string s = ReadLine ();
1583 bool CompareBytes (byte [] orig, byte [] other)
1585 for (int i = orig.Length - 1; i >= 0; i--)
1586 if (orig [i] != other [i])
1592 long MoveToNextBoundary ()
1595 bool got_cr = false;
1598 int c = data.ReadByte ();
1603 if (state == 0 && c == LF) {
1604 retval = data.Position - 1;
1608 c = data.ReadByte ();
1609 } else if (state == 0) {
1611 c = data.ReadByte ();
1612 } else if (state == 1 && c == '-') {
1613 c = data.ReadByte ();
1620 continue; // no ReadByte() here
1623 int nread = data.Read (buffer, 0, buffer.Length);
1624 int bl = buffer.Length;
1628 if (!CompareBytes (boundary_bytes, buffer)) {
1630 data.Position = retval + 2;
1635 c = data.ReadByte ();
1639 if (buffer [bl - 2] == '-' && buffer [bl - 1] == '-') {
1641 } else if (buffer [bl - 2] != CR || buffer [bl - 1] != LF) {
1643 data.Position = retval + 2;
1648 c = data.ReadByte ();
1651 data.Position = retval + 2;
1657 state = 0; // no ReadByte() here
1664 public Element ReadNextElement ()
1666 if (at_eof || ReadBoundary ())
1669 Element elem = new Element ();
1671 while ((header = ReadHeaders ()) != null) {
1672 if (StrUtils.StartsWith (header, "Content-Disposition:", true)) {
1673 elem.Name = GetContentDispositionAttribute (header, "name");
1674 elem.Filename = StripPath (GetContentDispositionAttributeWithEncoding (header, "filename"));
1675 } else if (StrUtils.StartsWith (header, "Content-Type:", true)) {
1676 elem.ContentType = header.Substring ("Content-Type:".Length).Trim ();
1680 long start = data.Position;
1682 long pos = MoveToNextBoundary ();
1686 elem.Length = pos - start;
1690 static string StripPath (string path)
1692 if (path == null || path.Length == 0)
1695 if (path.IndexOf (":\\") != 1)
1697 return path.Substring (path.LastIndexOf ("\\") + 1);