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 Stream input = GetSubStream (InputStream);
572 StreamReader s = new StreamReader (input, ContentEncoding);
574 StringBuilder key = new StringBuilder ();
575 StringBuilder value = new StringBuilder ();
578 while ((c = s.Read ()) != -1){
581 while ((c = s.Read ()) != -1){
583 AddRawKeyValue (key, value);
586 value.Append ((char) c);
589 AddRawKeyValue (key, value);
593 AddRawKeyValue (key, value);
595 key.Append ((char) c);
598 AddRawKeyValue (key, value);
600 EndSubStream (input);
603 bool IsContentType (string ct, bool starts_with)
606 return StrUtils.StartsWith (ContentType, ct, true);
608 return String.Compare (ContentType, ct, true, CultureInfo.InvariantCulture) == 0;
611 public NameValueCollection Form {
614 form = new WebROCollection ();
615 files = new HttpFileCollection ();
617 if (IsContentType ("multipart/form-data", true))
620 IsContentType ("application/x-www-form-urlencoded", true))
626 if (validate_form && !checked_form){
628 ValidateNameValueCollection ("Form", form);
635 public NameValueCollection Headers {
638 headers = new HeadersCollection (this);
644 public string HttpMethod {
646 if (http_method == null){
647 if (worker_request != null)
648 http_method = worker_request.GetHttpVerbName ();
656 void DoFilter (byte [] buffer)
658 if (input_filter == null || filter == null)
661 if (buffer.Length < 1024)
662 buffer = new byte [1024];
664 // Replace the input with the filtered input
665 input_filter.BaseStream = input_stream;
666 MemoryStream ms = new MemoryStream ();
668 int n = filter.Read (buffer, 0, buffer.Length);
671 ms.Write (buffer, 0, n);
673 // From now on input_stream has the filtered input
674 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
678 const int INPUT_BUFFER_SIZE = 32*1024;
680 TempFileStream GetTempStream ()
682 string tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
683 TempFileStream f = null;
685 Random rnd = new Random ();
690 path = System.IO.Path.Combine (tempdir, "tmp" + num.ToString("x") + ".req");
693 f = new TempFileStream (path);
694 } catch (SecurityException) {
695 // avoid an endless loop
703 void MakeInputStream ()
705 if (input_stream != null)
708 if (worker_request == null) {
709 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
710 DoFilter (new byte [1024]);
715 // Use an unmanaged memory block as this might be a large
718 int content_length = ContentLength;
721 HttpRuntimeSection config = (HttpRuntimeSection) WebConfigurationManager.GetSection ("system.web/httpRuntime");
723 HttpRuntimeConfig config = (HttpRuntimeConfig) HttpContext.GetAppConfig ("system.web/httpRuntime");
725 if ((content_length / 1024) > config.MaxRequestLength)
726 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
730 buffer = worker_request.GetPreloadedEntityBody ();
731 // we check the instance field 'content_length' here, not the local var.
732 if (this.content_length <= 0 || worker_request.IsEntireEntityBodyIsPreloaded ()) {
733 if (buffer == null || content_length == 0) {
734 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
736 input_stream = new MemoryStream (buffer, 0, buffer.Length, false, true);
738 DoFilter (new byte [1024]);
743 total = buffer.Length;
745 if (content_length > 0 && (content_length / 1024) >= config.RequestLengthDiskThreshold) {
746 // Writes the request to disk
747 total = Math.Min (content_length, total);
748 request_file = GetTempStream ();
749 Stream output = request_file;
751 output.Write (buffer, 0, total);
753 if (total < content_length) {
754 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
757 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
758 n = worker_request.ReadEntityBody (buffer, min);
761 output.Write (buffer, 0, n);
763 } while (total < content_length);
766 request_file.SetReadOnly ();
767 input_stream = request_file;
768 } else if (content_length > 0) {
769 // Buffers the request in an IntPtrStream
770 total = Math.Min (content_length, total);
771 IntPtr content = Marshal.AllocHGlobal (content_length);
772 if (content == (IntPtr) 0)
773 throw new HttpException (String.Format ("Not enough memory to allocate {0} bytes.",
777 Marshal.Copy (buffer, 0, content, total);
779 if (total < content_length) {
780 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
783 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
784 n = worker_request.ReadEntityBody (buffer, min);
787 Marshal.Copy (buffer, 0, (IntPtr) ((long)content + total), n);
789 } while (total < content_length);
792 input_stream = new IntPtrStream (content, total);
794 // Buffers the request in a MemoryStream or writes to disk if threshold exceeded
795 MemoryStream ms = new MemoryStream ();
798 ms.Write (buffer, 0, total);
800 buffer = new byte [INPUT_BUFFER_SIZE];
801 long maxlength = config.MaxRequestLength * 1024;
802 long disk_th = config.RequestLengthDiskThreshold * 1024;
805 n = worker_request.ReadEntityBody (buffer, INPUT_BUFFER_SIZE);
809 if (total < 0 || total > maxlength)
810 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
812 if (ms != null && total > disk_th) {
813 // Swith to on-disk file.
814 request_file = GetTempStream ();
815 ms.WriteTo (request_file);
817 output = request_file;
819 output.Write (buffer, 0, n);
823 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
825 request_file.SetReadOnly ();
826 input_stream = request_file;
831 if (total < content_length)
832 throw new HttpException (411, "The request body is incomplete.");
836 internal void ReleaseResources ()
839 if (input_stream != null){
840 stream = input_stream;
847 if (request_file != null) {
848 stream = request_file;
856 public Stream InputStream {
858 if (input_stream == null)
865 public bool IsAuthenticated {
867 if (context.User == null || context.User.Identity == null)
869 return context.User.Identity.IsAuthenticated;
873 public bool IsSecureConnection {
875 if (worker_request == null)
877 return worker_request.IsSecure ();
881 public string this [string key] {
882 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
884 // "The QueryString, Form, Cookies, or ServerVariables collection member
885 // specified in the key parameter."
886 string val = QueryString [key];
890 HttpCookie cookie = Cookies [key];
895 val = ServerVariables [key];
901 public NameValueCollection Params {
902 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
904 if (all_params == null)
905 all_params = new HttpParamsCollection (QueryString, Form, ServerVariables, Cookies);
913 if (unescaped_path == null) {
915 if (url_components != null) {
916 // use only if it's already been instantiated, so that we can't go into endless
917 // recursion in some scenarios
918 path = UrlComponents.Path;
921 path = ApplyUrlMapping (worker_request.GetUriPath ());
923 path = worker_request.GetUriPath ();
928 unescaped_path = Uri.UnescapeDataString (path);
930 unescaped_path = HttpUtility.UrlDecode (path);
934 return unescaped_path;
938 public string PathInfo {
940 if (path_info == null) {
941 if (worker_request == null)
943 path_info = worker_request.GetPathInfo ();
950 public string PhysicalApplicationPath {
952 if (worker_request == null)
953 throw new ArgumentNullException (); // like 2.0, 1.x throws TypeInitializationException
955 string path = HttpRuntime.AppDomainAppPath;
956 if (SecurityManager.SecurityEnabled) {
957 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
963 public string PhysicalPath {
965 if (worker_request == null)
966 return String.Empty; // don't check security with an empty string!
968 if (physical_path == null) {
969 // Don't call HttpRequest.MapPath here, as that one *trims* the input
970 physical_path = worker_request.MapPath (FilePath);
973 if (SecurityManager.SecurityEnabled) {
974 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, physical_path).Demand ();
976 return physical_path;
980 internal string RootVirtualDir {
982 if (root_virtual_dir == null){
983 string fp = FilePath;
984 int p = fp.LastIndexOf ('/');
987 root_virtual_dir = "/";
989 root_virtual_dir = fp.Substring (0, p);
991 return root_virtual_dir;
995 public NameValueCollection QueryString {
997 if (query_string_nvc == null) {
998 query_string_nvc = new WebROCollection ();
999 string q = UrlComponents.Query;
1004 HttpUtility.ParseQueryString (q, ContentEncoding, query_string_nvc);
1007 query_string_nvc.Protect();
1010 if (validate_query_string && !checked_query_string) {
1011 ValidateNameValueCollection ("QueryString", query_string_nvc);
1012 checked_query_string = true;
1015 return query_string_nvc;
1019 public string RawUrl {
1021 if (worker_request != null)
1022 return worker_request.GetRawUrl ();
1024 return UrlComponents.Path + UrlComponents.Query;
1031 public string RequestType {
1033 if (request_type == null){
1034 if (worker_request != null) {
1035 request_type = worker_request.GetHttpVerbName ();
1036 http_method = request_type;
1038 request_type = "GET";
1041 return request_type;
1045 request_type = value;
1049 public NameValueCollection ServerVariables {
1050 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
1052 if (server_variables == null)
1053 server_variables = new ServerVariablesCollection (this);
1055 return server_variables;
1059 public int TotalBytes {
1061 Stream ins = InputStream;
1062 return (int) ins.Length;
1068 if (cached_url == null) {
1069 if (orig_url == null)
1070 cached_url = UrlComponents.Uri;
1072 cached_url = new Uri (orig_url);
1079 public Uri UrlReferrer {
1081 if (worker_request == null)
1084 string hr = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderReferer);
1091 } catch (UriFormatException) {}
1096 public string UserAgent {
1098 if (worker_request == null)
1101 return worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderUserAgent);
1105 public string UserHostAddress {
1107 if (worker_request == null)
1110 return worker_request.GetRemoteAddress ();
1114 public string UserHostName {
1116 if (worker_request == null)
1119 return worker_request.GetRemoteName ();
1123 public string [] UserLanguages {
1125 if (worker_request == null)
1128 if (user_languages == null)
1129 user_languages = SplitHeader (HttpWorkerRequest.HeaderAcceptLanguage);
1131 return user_languages;
1135 public byte [] BinaryRead (int count)
1138 throw new ArgumentException ("count is < 0");
1140 Stream s = InputStream;
1141 byte [] ret = new byte [count];
1142 if (s.Read (ret, 0, count) != count)
1143 throw new ArgumentException (
1144 String.Format ("count {0} exceeds length of available input {1}",
1145 count, s.Length - s.Position));
1149 public int [] MapImageCoordinates (string imageFieldName)
1151 string method = HttpMethod;
1152 NameValueCollection coll = null;
1153 if (method == "HEAD" || method == "GET")
1155 else if (method == "POST")
1161 string x = coll [imageFieldName + ".x"];
1162 if (x == null || x == "")
1165 string y = coll [imageFieldName + ".y"];
1166 if (y == null || y == "")
1169 int [] result = new int [2];
1171 result [0] = Int32.Parse (x);
1172 result [1] = Int32.Parse (y);
1180 public string MapPath (string virtualPath)
1182 if (worker_request == null)
1185 return MapPath (virtualPath, BaseVirtualDir, true);
1188 public string MapPath (string virtualPath, string baseVirtualDir, bool allowCrossAppMapping)
1190 if (worker_request == null)
1191 throw new HttpException ("No HttpWorkerRequest");
1193 if (virtualPath == null)
1196 virtualPath = virtualPath.Trim ();
1197 if (virtualPath.Length == 0)
1201 if (virtualPath.IndexOf (':') != -1)
1202 throw new HttpException (String.Format ("'{0}' is not a valid virtual path.", virtualPath));
1204 string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
1206 if (!VirtualPathUtility.IsRooted (virtualPath)) {
1207 if (StrUtils.IsNullOrEmpty (baseVirtualDir))
1208 baseVirtualDir = appVirtualPath;
1209 virtualPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (baseVirtualDir), virtualPath);
1211 virtualPath = VirtualPathUtility.ToAbsolute (virtualPath);
1213 if (!allowCrossAppMapping){
1214 if (!StrUtils.StartsWith (virtualPath, appVirtualPath, true))
1215 throw new HttpException ("MapPath: Mapping across applications not allowed");
1216 if (appVirtualPath.Length > 1 && virtualPath.Length > 1 && virtualPath [0] != '/')
1217 throw new HttpException ("MapPath: Mapping across applications not allowed");
1220 return worker_request.MapPath (virtualPath);
1222 string path = worker_request.MapPath (virtualPath);
1223 if (virtualPath [virtualPath.Length - 1] != '/' && path [path.Length - 1] == System.IO.Path.DirectorySeparatorChar)
1224 path = path.TrimEnd (System.IO.Path.DirectorySeparatorChar);
1229 public void SaveAs (string filename, bool includeHeaders)
1231 Stream output = new FileStream (filename, FileMode.Create);
1232 if (includeHeaders) {
1233 StringBuilder sb = new StringBuilder ();
1234 string version = String.Empty;
1236 if (worker_request != null) {
1237 version = worker_request.GetHttpVersion ();
1238 path = UrlComponents.Path;
1240 string qs = UrlComponents.Query;
1242 sb.AppendFormat ("{0} {1}{2} {3}\r\n", HttpMethod, path, qs, version);
1243 NameValueCollection coll = Headers;
1244 foreach (string k in coll.AllKeys) {
1247 sb.Append (coll [k]);
1252 byte [] bytes = Encoding.GetEncoding (28591).GetBytes (sb.ToString ());
1253 output.Write (bytes, 0, bytes.Length);
1256 // More than 1 call to SaveAs works fine on MS, so we "copy" the stream
1257 // to keep InputStream in its state.
1258 Stream input = GetSubStream (InputStream);
1260 long len = input.Length;
1261 int buf_size = (int) Math.Min ((len < 0 ? 0 : len), 8192);
1262 byte [] data = new byte [buf_size];
1264 while (len > 0 && (count = input.Read (data, 0, buf_size)) > 0) {
1265 output.Write (data, 0, count);
1271 EndSubStream (input);
1275 public void ValidateInput ()
1277 validate_cookies = true;
1278 validate_query_string = true;
1279 validate_form = true;
1282 #region internal routines
1283 internal string ClientTarget {
1285 return client_target;
1289 client_target = value;
1300 string address = worker_request.GetRemoteAddress ();
1302 if (StrUtils.IsNullOrEmpty (address))
1305 if (address == "127.0.0.1")
1308 System.Net.IPAddress remoteAddr = System.Net.IPAddress.Parse (address);
1309 if (System.Net.IPAddress.IsLoopback (remoteAddr))
1312 for (int i = 0; i < host_addresses.Length; i++)
1313 if (remoteAddr.Equals (host_addresses [i]))
1320 internal void SetFilePath (string path)
1323 physical_path = null;
1326 internal void SetCurrentExePath (string path)
1329 current_exe_path = path;
1330 UrlComponents.Path = path;
1331 // recreated on demand
1332 root_virtual_dir = null;
1333 base_virtual_dir = null;
1334 physical_path = null;
1335 unescaped_path = null;
1338 internal void SetPathInfo (string pi)
1344 // Headers is ReadOnly, so we need this hack for cookie-less sessions.
1345 internal void SetHeader (string name, string value)
1347 WebROCollection h = (WebROCollection) Headers;
1353 // Notice: there is nothing raw about this querystring.
1354 internal string QueryStringRaw {
1356 if (url_components == null)
1357 return worker_request.GetQueryString ();
1359 return UrlComponents.Query;
1363 UrlComponents.Query = value;
1365 query_string_nvc = null;
1369 // Internal, dont know what it does, so flagged as public so we can see it.
1370 internal void SetForm (WebROCollection coll)
1375 internal HttpWorkerRequest WorkerRequest {
1377 return worker_request;
1381 internal HttpContext Context {
1387 static void ValidateNameValueCollection (string name, NameValueCollection coll)
1392 foreach (string key in coll.Keys) {
1393 string val = coll [key];
1394 if (val != null && val != "" && CheckString (val))
1395 ThrowValidationException (name, key, val);
1399 static void ValidateCookieCollection (HttpCookieCollection cookies)
1401 if (cookies == null)
1404 int size = cookies.Count;
1406 for (int i = 0 ; i < size ; i++) {
1407 cookie = cookies[i];
1408 string value = cookie.Value;
1410 if (value != null && value != "" && CheckString (value))
1411 ThrowValidationException ("Cookies", cookie.Name, cookie.Value);
1415 static void ThrowValidationException (string name, string key, string value)
1417 string v = "\"" + value + "\"";
1419 v = v.Substring (0, 16) + "...\"";
1421 string msg = String.Format ("A potentially dangerous Request.{0} value was " +
1422 "detected from the client ({1}={2}).", name, key, v);
1424 throw new HttpRequestValidationException (msg);
1427 static bool CheckString (string val)
1429 int len = val.Length;
1433 char current = val [0];
1434 for (int idx = 1; idx < len; idx++) {
1435 char next = val [idx];
1436 if (current == '<' || current == '\xff1c') {
1437 if (next == '!' || next < ' '
1438 || (next >= 'a' && next <= 'z')
1439 || (next >= 'A' && next <= 'Z'))
1441 } else if (current == '&' && next == '#') {
1451 static System.Net.IPAddress [] GetLocalHostAddresses ()
1454 string hostName = System.Net.Dns.GetHostName ();
1456 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostAddresses (hostName);
1458 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostByName (hostName).AddressList;
1464 return new System.Net.IPAddress[0];
1470 #region Helper classes
1473 // Stream-based multipart handling.
1475 // In this incarnation deals with an HttpInputStream as we are now using
1476 // IntPtr-based streams instead of byte []. In the future, we will also
1477 // send uploads above a certain threshold into the disk (to implement
1478 // limit-less HttpInputFiles).
1481 class HttpMultipart {
1483 public class Element {
1484 public string ContentType;
1486 public string Filename;
1490 public override string ToString ()
1492 return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
1493 Start.ToString () + ", Length " + Length.ToString ();
1499 byte [] boundary_bytes;
1505 const byte HYPHEN = (byte) '-', LF = (byte) '\n', CR = (byte) '\r';
1508 // In the case of multipart entities, in which one or more different
1509 // sets of data are combined in a single body, a "multipart" media type
1510 // field must appear in the entity's header. The body must then contain
1511 // one or more body parts, each preceded by a boundary delimiter line,
1512 // and the last one followed by a closing boundary delimiter line.
1513 // After its boundary delimiter line, each body part then consists of a
1514 // header area, a blank line, and a body area. Thus a body part is
1515 // similar to an RFC 822 message in syntax, but different in meaning.
1517 public HttpMultipart (Stream data, string b, Encoding encoding)
1521 boundary_bytes = encoding.GetBytes (b);
1522 buffer = new byte [boundary_bytes.Length + 2]; // CRLF or '--'
1523 this.encoding = encoding;
1524 sb = new StringBuilder ();
1529 // CRLF or LF are ok as line endings.
1530 bool got_cr = false;
1534 b = data.ReadByte ();
1543 sb.Append ((char) b);
1549 return sb.ToString ();
1553 static string GetContentDispositionAttribute (string l, string name)
1555 int idx = l.IndexOf (name + "=\"");
1558 int begin = idx + name.Length + "=\"".Length;
1559 int end = l.IndexOf ('"', begin);
1564 return l.Substring (begin, end - begin);
1567 string GetContentDispositionAttributeWithEncoding (string l, string name)
1569 int idx = l.IndexOf (name + "=\"");
1572 int begin = idx + name.Length + "=\"".Length;
1573 int end = l.IndexOf ('"', begin);
1579 string temp = l.Substring (begin, end - begin);
1580 byte [] source = new byte [temp.Length];
1581 for (int i = temp.Length - 1; i >= 0; i--)
1582 source [i] = (byte) temp [i];
1584 return encoding.GetString (source);
1587 bool ReadBoundary ()
1590 string line = ReadLine ();
1593 if (line [0] != '-' || line [1] != '-')
1596 if (!StrUtils.EndsWith (line, boundary, false))
1604 string ReadHeaders ()
1606 string s = ReadLine ();
1613 bool CompareBytes (byte [] orig, byte [] other)
1615 for (int i = orig.Length - 1; i >= 0; i--)
1616 if (orig [i] != other [i])
1622 long MoveToNextBoundary ()
1625 bool got_cr = false;
1628 int c = data.ReadByte ();
1633 if (state == 0 && c == LF) {
1634 retval = data.Position - 1;
1638 c = data.ReadByte ();
1639 } else if (state == 0) {
1641 c = data.ReadByte ();
1642 } else if (state == 1 && c == '-') {
1643 c = data.ReadByte ();
1650 continue; // no ReadByte() here
1653 int nread = data.Read (buffer, 0, buffer.Length);
1654 int bl = buffer.Length;
1658 if (!CompareBytes (boundary_bytes, buffer)) {
1660 data.Position = retval + 2;
1665 c = data.ReadByte ();
1669 if (buffer [bl - 2] == '-' && buffer [bl - 1] == '-') {
1671 } else if (buffer [bl - 2] != CR || buffer [bl - 1] != LF) {
1673 data.Position = retval + 2;
1678 c = data.ReadByte ();
1681 data.Position = retval + 2;
1687 state = 0; // no ReadByte() here
1694 public Element ReadNextElement ()
1696 if (at_eof || ReadBoundary ())
1699 Element elem = new Element ();
1701 while ((header = ReadHeaders ()) != null) {
1702 if (StrUtils.StartsWith (header, "Content-Disposition:", true)) {
1703 elem.Name = GetContentDispositionAttribute (header, "name");
1704 elem.Filename = StripPath (GetContentDispositionAttributeWithEncoding (header, "filename"));
1705 } else if (StrUtils.StartsWith (header, "Content-Type:", true)) {
1706 elem.ContentType = header.Substring ("Content-Type:".Length).Trim ();
1710 long start = data.Position;
1712 long pos = MoveToNextBoundary ();
1716 elem.Length = pos - start;
1720 static string StripPath (string path)
1722 if (path == null || path.Length == 0)
1725 if (path.IndexOf (":\\") != 1)
1727 return path.Substring (path.LastIndexOf ("\\") + 1);