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.Security.Principal;
40 using System.Web.Configuration;
42 using System.Web.Util;
43 using System.Globalization;
45 namespace System.Web {
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;
52 WebROCollection query_string_nvc;
56 string orig_url = null;
57 UriBuilder url_components;
62 // On-demand computed values
64 HttpBrowserCapabilities browser_capabilities;
65 string file_path, base_virtual_dir, root_virtual_dir;
67 int content_length = -1;
69 string current_exe_path;
71 string unescaped_path;
73 WebROCollection all_params;
74 WebROCollection headers;
76 InputFilterStream input_filter;
78 HttpCookieCollection cookies;
82 HttpFileCollection files;
84 ServerVariablesCollection server_variables;
85 HttpClientCertificate client_cert;
88 string [] accept_types;
89 string [] user_languages;
91 TempFileStream request_file;
93 readonly static System.Net.IPAddress [] host_addresses;
96 bool validate_cookies, validate_query_string, validate_form;
97 bool checked_cookies, checked_query_string, checked_form;
99 readonly static char [] queryTrimChars = {'?'};
101 static HttpRequest ()
103 host_addresses = GetLocalHostAddresses ();
106 public HttpRequest (string filename, string url, string queryString)
108 // warning 169: what are we supposed to do with filename?
110 //this.filename = filename;
113 url_components = new UriBuilder (url);
114 url_components.Query = queryString;
116 query_string_nvc = new WebROCollection ();
117 if (queryString != null)
118 HttpUtility.ParseQueryString (queryString, Encoding.Default, query_string_nvc);
119 query_string_nvc.Protect ();
122 internal HttpRequest (HttpWorkerRequest worker_request, HttpContext context)
124 this.worker_request = worker_request;
125 this.context = context;
128 internal UriBuilder UrlComponents {
130 if (url_components == null) {
132 byte[] queryStringRaw = worker_request.GetQueryStringRawBytes();
133 if(queryStringRaw != null)
134 query = ContentEncoding.GetString(queryStringRaw);
136 query = worker_request.GetQueryString();
140 ApplyUrlMapping (worker_request.GetUriPath ()),
142 worker_request.GetUriPath (),
146 return url_components;
150 void BuildUrlComponents (string path, string query)
152 if (url_components != null)
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);
164 internal string ApplyUrlMapping (string url)
166 if (WebConfigurationManager.HasConfigErrors)
169 UrlMappingsSection ums = WebConfigurationManager.GetSection ("system.web/urlMappings", ApplicationPath) as UrlMappingsSection;
170 UrlMappingCollection umc;
172 if (ums == null || !ums.IsEnabled || (umc = ums.UrlMappings).Count == 0)
175 string relUrl = VirtualPathUtility.ToAppRelative (url);
176 UrlMapping um = null;
178 foreach (UrlMapping u in umc) {
181 if (String.Compare (relUrl, u.Url, StringComparison.Ordinal) == 0) {
190 string rawUrl = VirtualPathUtility.ToAbsolute (um.MappedUrl.Trim ());
191 Uri newUrl = new Uri ("http://host.com" + rawUrl);
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 ();
200 BuildUrlComponents (newUrl.AbsolutePath, newUrl.Query);
202 return url_components.Path;
206 string [] SplitHeader (int header_index)
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 ();
218 public string [] AcceptTypes {
220 if (worker_request == null)
223 if (accept_types == null)
224 accept_types = SplitHeader (HttpWorkerRequest.HeaderAccept);
232 public WindowsIdentity LogonUserIdentity {
233 get { throw new NotImplementedException (); }
238 public string AnonymousID {
243 anonymous_id = value;
248 public string ApplicationPath {
250 if (worker_request == null)
252 return worker_request.GetAppPath ();
256 public HttpBrowserCapabilities Browser {
258 if (browser_capabilities == null)
259 browser_capabilities = (HttpBrowserCapabilities)
260 HttpCapabilitiesBase.GetConfigCapabilities (null, this);
262 return browser_capabilities;
266 browser_capabilities = value;
271 internal bool BrowserMightHaveSpecialWriter {
273 return (browser_capabilities != null
274 || HttpApplicationFactory.AppBrowsersFiles.Length > 0);
278 internal bool BrowserMightHaveAdapters {
280 return (browser_capabilities != null
281 || HttpApplicationFactory.AppBrowsersFiles.Length > 0);
286 public HttpClientCertificate ClientCertificate {
288 if (client_cert == null)
289 client_cert = new HttpClientCertificate (worker_request);
294 static internal string GetParameter (string header, string attr)
296 int ap = header.IndexOf (attr);
301 if (ap >= header.Length)
304 char ending = header [ap];
308 int end = header.IndexOf (ending, ap+1);
310 return (ending == '"') ? null : header.Substring (ap);
312 return header.Substring (ap+1, end-ap-1);
315 public Encoding ContentEncoding {
317 if (encoding == null){
318 if (worker_request == null)
319 throw new HttpException ("No HttpWorkerRequest");
321 string content_type = ContentType;
322 string parameter = GetParameter (content_type, "; charset=");
323 if (parameter == null) {
324 encoding = WebEncoding.RequestEncoding;
327 // Do what the #1 web server does
328 encoding = Encoding.GetEncoding (parameter);
330 encoding = WebEncoding.RequestEncoding;
342 public int ContentLength {
344 if (content_length == -1){
345 if (worker_request == null)
348 string cl = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentLength);
352 content_length = Int32.Parse (cl);
357 // content_length will still be < 0, but we know we gotta read from the client
358 if (content_length < 0)
361 return content_length;
365 public string ContentType {
367 if (content_type == null){
368 if (worker_request != null)
369 content_type = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentType);
371 if (content_type == null)
372 content_type = String.Empty;
379 content_type = value;
383 public HttpCookieCollection Cookies {
385 if (cookies == null) {
386 if (worker_request == null) {
387 cookies = new HttpCookieCollection ();
389 string cookie_hv = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderCookie);
390 cookies = new HttpCookieCollection (cookie_hv);
395 // For J2EE portal support we emulate cookies using the session.
396 GetSessionCookiesForPortal (cookies);
398 if (validate_cookies && !checked_cookies){
399 ValidateCookieCollection (cookies);
400 checked_cookies = true;
408 public string CurrentExecutionFilePath {
410 if (current_exe_path != null)
411 return current_exe_path;
418 public string AppRelativeCurrentExecutionFilePath {
420 return VirtualPathUtility.ToAppRelative (CurrentExecutionFilePath);
425 public string FilePath {
427 if (worker_request == null)
428 return "/"; // required for 2.0
430 if (file_path == null)
431 file_path = UrlUtils.Canonic (
433 ApplyUrlMapping (worker_request.GetFilePath ())
435 worker_request.GetFilePath ()
443 internal string BaseVirtualDir {
445 if (base_virtual_dir == null){
446 base_virtual_dir = FilePath;
447 int p = base_virtual_dir.LastIndexOf ('/');
449 base_virtual_dir = base_virtual_dir.Substring (0, p);
451 return base_virtual_dir;
455 public HttpFileCollection Files {
458 files = new HttpFileCollection ();
459 if ((worker_request != null) && IsContentType ("multipart/form-data", true)) {
460 form = new WebROCollection ();
469 public Stream Filter {
474 if (input_filter == null)
475 input_filter = new InputFilterStream ();
481 // This checks that get_ was called before.
482 if (input_filter == null)
483 throw new HttpException ("Invalid filter");
489 // GetSubStream returns a 'copy' of the InputStream with Position set to 0.
490 static Stream GetSubStream (Stream stream)
493 if (stream is IntPtrStream)
494 return new IntPtrStream (stream);
497 if (stream is MemoryStream) {
498 MemoryStream other = (MemoryStream) stream;
499 return new MemoryStream (other.GetBuffer (), 0, (int) other.Length, false, true);
502 if (stream is TempFileStream) {
503 ((TempFileStream) stream).SavePosition ();
507 throw new NotSupportedException ("The stream is " + stream.GetType ());
510 static void EndSubStream (Stream stream)
512 if (stream is TempFileStream) {
513 ((TempFileStream) stream).RestorePosition ();
518 // Loads the data on the form for multipart/form-data
520 void LoadMultiPart ()
522 string boundary = GetParameter (ContentType, "; boundary=");
523 if (boundary == null)
526 Stream input = GetSubStream (InputStream);
527 HttpMultipart multi_part = new HttpMultipart (input, boundary, ContentEncoding);
529 HttpMultipart.Element e;
530 while ((e = multi_part.ReadNextElement ()) != null) {
531 if (e.Filename == null){
532 byte [] copy = new byte [e.Length];
534 input.Position = e.Start;
535 input.Read (copy, 0, (int) e.Length);
537 form.Add (e.Name, ContentEncoding.GetString (copy));
540 // We use a substream, as in 2.x we will support large uploads streamed to disk,
542 HttpPostedFile sub = new HttpPostedFile (e.Filename, e.ContentType, input, e.Start, e.Length);
543 files.AddFile (e.Name, sub);
546 EndSubStream (input);
550 // Adds the key/value to the form, and sets the argumets to empty
552 void AddRawKeyValue (StringBuilder key, StringBuilder value)
554 string decodedKey = HttpUtility.UrlDecode (key.ToString (), ContentEncoding);
555 form.Add (decodedKey,
556 HttpUtility.UrlDecode (value.ToString (), ContentEncoding));
563 // Loads the form data from on a application/x-www-form-urlencoded post
566 void RawLoadWwwForm ()
571 using (Stream input = GetSubStream (InputStream)) {
572 using (StreamReader s = new StreamReader (input, ContentEncoding)) {
573 StringBuilder key = new StringBuilder ();
574 StringBuilder value = new StringBuilder ();
577 while ((c = s.Read ()) != -1){
580 while ((c = s.Read ()) != -1){
582 AddRawKeyValue (key, value);
585 value.Append ((char) c);
588 AddRawKeyValue (key, value);
592 AddRawKeyValue (key, value);
594 key.Append ((char) c);
597 AddRawKeyValue (key, value);
599 EndSubStream (input);
604 bool IsContentType (string ct, bool starts_with)
607 return StrUtils.StartsWith (ContentType, ct, true);
609 return String.Compare (ContentType, ct, true, CultureInfo.InvariantCulture) == 0;
612 public NameValueCollection Form {
615 form = new WebROCollection ();
616 files = new HttpFileCollection ();
618 if (IsContentType ("multipart/form-data", true))
621 IsContentType ("application/x-www-form-urlencoded", true))
627 if (validate_form && !checked_form){
629 ValidateNameValueCollection ("Form", form);
636 public NameValueCollection Headers {
639 headers = new HeadersCollection (this);
645 public string HttpMethod {
647 if (http_method == null){
648 if (worker_request != null)
649 http_method = worker_request.GetHttpVerbName ();
657 void DoFilter (byte [] buffer)
659 if (input_filter == null || filter == null)
662 if (buffer.Length < 1024)
663 buffer = new byte [1024];
665 // Replace the input with the filtered input
666 input_filter.BaseStream = input_stream;
667 MemoryStream ms = new MemoryStream ();
669 int n = filter.Read (buffer, 0, buffer.Length);
672 ms.Write (buffer, 0, n);
674 // From now on input_stream has the filtered input
675 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
679 const int INPUT_BUFFER_SIZE = 32*1024;
681 TempFileStream GetTempStream ()
683 string tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
684 TempFileStream f = null;
686 Random rnd = new Random ();
691 path = System.IO.Path.Combine (tempdir, "tmp" + num.ToString("x") + ".req");
694 f = new TempFileStream (path);
695 } catch (SecurityException) {
696 // avoid an endless loop
704 void MakeInputStream ()
706 if (input_stream != null)
709 if (worker_request == null) {
710 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
711 DoFilter (new byte [1024]);
716 // Use an unmanaged memory block as this might be a large
719 int content_length = ContentLength;
722 HttpRuntimeSection config = (HttpRuntimeSection) WebConfigurationManager.GetSection ("system.web/httpRuntime");
724 HttpRuntimeConfig config = (HttpRuntimeConfig) HttpContext.GetAppConfig ("system.web/httpRuntime");
726 if ((content_length / 1024) > config.MaxRequestLength)
727 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
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);
737 input_stream = new MemoryStream (buffer, 0, buffer.Length, false, true);
739 DoFilter (new byte [1024]);
744 total = buffer.Length;
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;
752 output.Write (buffer, 0, total);
754 if (total < content_length) {
755 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
758 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
759 n = worker_request.ReadEntityBody (buffer, min);
762 output.Write (buffer, 0, n);
764 } while (total < content_length);
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.",
778 Marshal.Copy (buffer, 0, content, total);
780 if (total < content_length) {
781 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
784 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
785 n = worker_request.ReadEntityBody (buffer, min);
788 Marshal.Copy (buffer, 0, (IntPtr) ((long)content + total), n);
790 } while (total < content_length);
793 input_stream = new IntPtrStream (content, total);
795 // Buffers the request in a MemoryStream or writes to disk if threshold exceeded
796 MemoryStream ms = new MemoryStream ();
799 ms.Write (buffer, 0, total);
801 buffer = new byte [INPUT_BUFFER_SIZE];
802 long maxlength = config.MaxRequestLength * 1024;
803 long disk_th = config.RequestLengthDiskThreshold * 1024;
806 n = worker_request.ReadEntityBody (buffer, INPUT_BUFFER_SIZE);
810 if (total < 0 || total > maxlength)
811 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
813 if (ms != null && total > disk_th) {
814 // Swith to on-disk file.
815 request_file = GetTempStream ();
816 ms.WriteTo (request_file);
818 output = request_file;
820 output.Write (buffer, 0, n);
824 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
826 request_file.SetReadOnly ();
827 input_stream = request_file;
832 if (total < content_length)
833 throw new HttpException (411, "The request body is incomplete.");
837 internal void ReleaseResources ()
840 if (input_stream != null){
841 stream = input_stream;
848 if (request_file != null) {
849 stream = request_file;
857 public Stream InputStream {
859 if (input_stream == null)
866 public bool IsAuthenticated {
868 if (context.User == null || context.User.Identity == null)
870 return context.User.Identity.IsAuthenticated;
874 public bool IsSecureConnection {
876 if (worker_request == null)
878 return worker_request.IsSecure ();
882 public string this [string key] {
883 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
885 // "The QueryString, Form, Cookies, or ServerVariables collection member
886 // specified in the key parameter."
887 string val = QueryString [key];
891 HttpCookie cookie = Cookies [key];
896 val = ServerVariables [key];
902 public NameValueCollection Params {
903 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
905 if (all_params == null)
906 all_params = new HttpParamsCollection (QueryString, Form, ServerVariables, Cookies);
914 if (unescaped_path == null) {
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;
922 path = ApplyUrlMapping (worker_request.GetUriPath ());
924 path = worker_request.GetUriPath ();
929 unescaped_path = Uri.UnescapeDataString (path);
931 unescaped_path = HttpUtility.UrlDecode (path);
935 return unescaped_path;
939 public string PathInfo {
941 if (path_info == null) {
942 if (worker_request == null)
944 path_info = worker_request.GetPathInfo ();
951 public string PhysicalApplicationPath {
953 if (worker_request == null)
954 throw new ArgumentNullException (); // like 2.0, 1.x throws TypeInitializationException
956 string path = HttpRuntime.AppDomainAppPath;
957 if (SecurityManager.SecurityEnabled) {
958 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
964 public string PhysicalPath {
966 if (worker_request == null)
967 return String.Empty; // don't check security with an empty string!
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);
974 if (SecurityManager.SecurityEnabled) {
975 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, physical_path).Demand ();
977 return physical_path;
981 internal string RootVirtualDir {
983 if (root_virtual_dir == null){
984 string fp = FilePath;
985 int p = fp.LastIndexOf ('/');
988 root_virtual_dir = "/";
990 root_virtual_dir = fp.Substring (0, p);
992 return root_virtual_dir;
996 public NameValueCollection QueryString {
998 if (query_string_nvc == null) {
999 query_string_nvc = new WebROCollection ();
1000 string q = UrlComponents.Query;
1005 HttpUtility.ParseQueryString (q, ContentEncoding, query_string_nvc);
1008 query_string_nvc.Protect();
1011 if (validate_query_string && !checked_query_string) {
1012 ValidateNameValueCollection ("QueryString", query_string_nvc);
1013 checked_query_string = true;
1016 return query_string_nvc;
1020 public string RawUrl {
1022 if (worker_request != null)
1023 return worker_request.GetRawUrl ();
1025 return UrlComponents.Path + UrlComponents.Query;
1032 public string RequestType {
1034 if (request_type == null){
1035 if (worker_request != null) {
1036 request_type = worker_request.GetHttpVerbName ();
1037 http_method = request_type;
1039 request_type = "GET";
1042 return request_type;
1046 request_type = value;
1050 public NameValueCollection ServerVariables {
1051 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
1053 if (server_variables == null)
1054 server_variables = new ServerVariablesCollection (this);
1056 return server_variables;
1060 public int TotalBytes {
1062 Stream ins = InputStream;
1063 return (int) ins.Length;
1069 if (cached_url == null) {
1070 if (orig_url == null)
1071 cached_url = UrlComponents.Uri;
1073 cached_url = new Uri (orig_url);
1080 public Uri UrlReferrer {
1082 if (worker_request == null)
1085 string hr = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderReferer);
1092 } catch (UriFormatException) {}
1097 public string UserAgent {
1099 if (worker_request == null)
1102 return worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderUserAgent);
1106 public string UserHostAddress {
1108 if (worker_request == null)
1111 return worker_request.GetRemoteAddress ();
1115 public string UserHostName {
1117 if (worker_request == null)
1120 return worker_request.GetRemoteName ();
1124 public string [] UserLanguages {
1126 if (worker_request == null)
1129 if (user_languages == null)
1130 user_languages = SplitHeader (HttpWorkerRequest.HeaderAcceptLanguage);
1132 return user_languages;
1136 public byte [] BinaryRead (int count)
1139 throw new ArgumentException ("count is < 0");
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));
1150 public int [] MapImageCoordinates (string imageFieldName)
1152 string method = HttpMethod;
1153 NameValueCollection coll = null;
1154 if (method == "HEAD" || method == "GET")
1156 else if (method == "POST")
1162 string x = coll [imageFieldName + ".x"];
1163 if (x == null || x == "")
1166 string y = coll [imageFieldName + ".y"];
1167 if (y == null || y == "")
1170 int [] result = new int [2];
1172 result [0] = Int32.Parse (x);
1173 result [1] = Int32.Parse (y);
1181 public string MapPath (string virtualPath)
1183 if (worker_request == null)
1186 return MapPath (virtualPath, BaseVirtualDir, true);
1189 public string MapPath (string virtualPath, string baseVirtualDir, bool allowCrossAppMapping)
1191 if (worker_request == null)
1192 throw new HttpException ("No HttpWorkerRequest");
1194 if (virtualPath == null)
1197 virtualPath = virtualPath.Trim ();
1198 if (virtualPath.Length == 0)
1202 if (virtualPath.IndexOf (':') != -1)
1203 throw new HttpException (String.Format ("'{0}' is not a valid virtual path.", virtualPath));
1205 string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
1207 if (!VirtualPathUtility.IsRooted (virtualPath)) {
1208 if (StrUtils.IsNullOrEmpty (baseVirtualDir))
1209 baseVirtualDir = appVirtualPath;
1210 virtualPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (baseVirtualDir), virtualPath);
1212 virtualPath = VirtualPathUtility.ToAbsolute (virtualPath);
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");
1221 return worker_request.MapPath (virtualPath);
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);
1230 public void SaveAs (string filename, bool includeHeaders)
1232 Stream output = new FileStream (filename, FileMode.Create);
1233 if (includeHeaders) {
1234 StringBuilder sb = new StringBuilder ();
1235 string version = String.Empty;
1237 if (worker_request != null) {
1238 version = worker_request.GetHttpVersion ();
1239 path = UrlComponents.Path;
1241 string qs = UrlComponents.Query;
1243 sb.AppendFormat ("{0} {1}{2} {3}\r\n", HttpMethod, path, qs, version);
1244 NameValueCollection coll = Headers;
1245 foreach (string k in coll.AllKeys) {
1248 sb.Append (coll [k]);
1253 byte [] bytes = Encoding.GetEncoding (28591).GetBytes (sb.ToString ());
1254 output.Write (bytes, 0, bytes.Length);
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);
1261 long len = input.Length;
1262 int buf_size = (int) Math.Min ((len < 0 ? 0 : len), 8192);
1263 byte [] data = new byte [buf_size];
1265 while (len > 0 && (count = input.Read (data, 0, buf_size)) > 0) {
1266 output.Write (data, 0, count);
1272 EndSubStream (input);
1276 public void ValidateInput ()
1278 validate_cookies = true;
1279 validate_query_string = true;
1280 validate_form = true;
1283 #region internal routines
1284 internal string ClientTarget {
1286 return client_target;
1290 client_target = value;
1301 string address = worker_request.GetRemoteAddress ();
1303 if (StrUtils.IsNullOrEmpty (address))
1306 if (address == "127.0.0.1")
1309 System.Net.IPAddress remoteAddr = System.Net.IPAddress.Parse (address);
1310 if (System.Net.IPAddress.IsLoopback (remoteAddr))
1313 for (int i = 0; i < host_addresses.Length; i++)
1314 if (remoteAddr.Equals (host_addresses [i]))
1321 internal void SetFilePath (string path)
1324 physical_path = null;
1327 internal void SetCurrentExePath (string path)
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;
1339 internal void SetPathInfo (string pi)
1345 // Headers is ReadOnly, so we need this hack for cookie-less sessions.
1346 internal void SetHeader (string name, string value)
1348 WebROCollection h = (WebROCollection) Headers;
1354 // Notice: there is nothing raw about this querystring.
1355 internal string QueryStringRaw {
1357 UriBuilder urlComponents = UrlComponents;
1359 if (urlComponents == null) {
1360 string ret = worker_request.GetQueryString ();
1362 if (ret == null || ret.Length == 0)
1363 return String.Empty;
1371 return UrlComponents.Query;
1375 UrlComponents.Query = value;
1377 query_string_nvc = null;
1381 // Internal, dont know what it does, so flagged as public so we can see it.
1382 internal void SetForm (WebROCollection coll)
1387 internal HttpWorkerRequest WorkerRequest {
1389 return worker_request;
1393 internal HttpContext Context {
1399 static void ValidateNameValueCollection (string name, NameValueCollection coll)
1404 foreach (string key in coll.Keys) {
1405 string val = coll [key];
1406 if (val != null && val != "" && CheckString (val))
1407 ThrowValidationException (name, key, val);
1411 static void ValidateCookieCollection (HttpCookieCollection cookies)
1413 if (cookies == null)
1416 int size = cookies.Count;
1418 for (int i = 0 ; i < size ; i++) {
1419 cookie = cookies[i];
1420 string value = cookie.Value;
1422 if (value != null && value != "" && CheckString (value))
1423 ThrowValidationException ("Cookies", cookie.Name, cookie.Value);
1427 static void ThrowValidationException (string name, string key, string value)
1429 string v = "\"" + value + "\"";
1431 v = v.Substring (0, 16) + "...\"";
1433 string msg = String.Format ("A potentially dangerous Request.{0} value was " +
1434 "detected from the client ({1}={2}).", name, key, v);
1436 throw new HttpRequestValidationException (msg);
1439 static bool CheckString (string val)
1441 int len = val.Length;
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'))
1453 } else if (current == '&' && next == '#') {
1463 static System.Net.IPAddress [] GetLocalHostAddresses ()
1466 string hostName = System.Net.Dns.GetHostName ();
1468 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostAddresses (hostName);
1470 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostByName (hostName).AddressList;
1476 return new System.Net.IPAddress[0];
1482 #region Helper classes
1485 // Stream-based multipart handling.
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).
1493 class HttpMultipart {
1495 public class Element {
1496 public string ContentType;
1498 public string Filename;
1502 public override string ToString ()
1504 return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
1505 Start.ToString () + ", Length " + Length.ToString ();
1511 byte [] boundary_bytes;
1517 const byte HYPHEN = (byte) '-', LF = (byte) '\n', CR = (byte) '\r';
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.
1529 public HttpMultipart (Stream data, string b, Encoding encoding)
1533 boundary_bytes = encoding.GetBytes (b);
1534 buffer = new byte [boundary_bytes.Length + 2]; // CRLF or '--'
1535 this.encoding = encoding;
1536 sb = new StringBuilder ();
1541 // CRLF or LF are ok as line endings.
1542 bool got_cr = false;
1546 b = data.ReadByte ();
1555 sb.Append ((char) b);
1561 return sb.ToString ();
1565 static string GetContentDispositionAttribute (string l, string name)
1567 int idx = l.IndexOf (name + "=\"");
1570 int begin = idx + name.Length + "=\"".Length;
1571 int end = l.IndexOf ('"', begin);
1576 return l.Substring (begin, end - begin);
1579 string GetContentDispositionAttributeWithEncoding (string l, string name)
1581 int idx = l.IndexOf (name + "=\"");
1584 int begin = idx + name.Length + "=\"".Length;
1585 int end = l.IndexOf ('"', begin);
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];
1596 return encoding.GetString (source);
1599 bool ReadBoundary ()
1602 string line = ReadLine ();
1605 if (line [0] != '-' || line [1] != '-')
1608 if (!StrUtils.EndsWith (line, boundary, false))
1616 string ReadHeaders ()
1618 string s = ReadLine ();
1625 bool CompareBytes (byte [] orig, byte [] other)
1627 for (int i = orig.Length - 1; i >= 0; i--)
1628 if (orig [i] != other [i])
1634 long MoveToNextBoundary ()
1637 bool got_cr = false;
1640 int c = data.ReadByte ();
1645 if (state == 0 && c == LF) {
1646 retval = data.Position - 1;
1650 c = data.ReadByte ();
1651 } else if (state == 0) {
1653 c = data.ReadByte ();
1654 } else if (state == 1 && c == '-') {
1655 c = data.ReadByte ();
1662 continue; // no ReadByte() here
1665 int nread = data.Read (buffer, 0, buffer.Length);
1666 int bl = buffer.Length;
1670 if (!CompareBytes (boundary_bytes, buffer)) {
1672 data.Position = retval + 2;
1677 c = data.ReadByte ();
1681 if (buffer [bl - 2] == '-' && buffer [bl - 1] == '-') {
1683 } else if (buffer [bl - 2] != CR || buffer [bl - 1] != LF) {
1685 data.Position = retval + 2;
1690 c = data.ReadByte ();
1693 data.Position = retval + 2;
1699 state = 0; // no ReadByte() here
1706 public Element ReadNextElement ()
1708 if (at_eof || ReadBoundary ())
1711 Element elem = new Element ();
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 ();
1722 long start = data.Position;
1724 long pos = MoveToNextBoundary ();
1728 elem.Length = pos - start;
1732 static string StripPath (string path)
1734 if (path == null || path.Length == 0)
1737 if (path.IndexOf (":\\") != 1)
1739 return path.Substring (path.LastIndexOf ("\\") + 1);