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;
100 host_addresses = GetLocalHostAddresses ();
103 public HttpRequest (string filename, string url, string queryString)
105 // warning 169: what are we supposed to do with filename?
107 //this.filename = filename;
110 url_components = new UriBuilder (url);
111 url_components.Query = queryString;
113 query_string_nvc = new WebROCollection ();
114 HttpUtility.ParseQueryString (queryString, Encoding.Default, query_string_nvc);
115 query_string_nvc.Protect ();
118 UriBuilder UrlComponents {
120 if (url_components == null) {
121 url_components = new UriBuilder ();
122 url_components.Scheme = worker_request.GetProtocol ();
123 url_components.Host = worker_request.GetServerName ();
124 url_components.Port = worker_request.GetLocalPort ();
125 url_components.Path = worker_request.GetUriPath ();
127 byte[] queryStringRaw = worker_request.GetQueryStringRawBytes();
128 if(queryStringRaw != null)
129 url_components.Query = ContentEncoding.GetString(queryStringRaw);
131 url_components.Query = worker_request.GetQueryString();
133 return url_components;
137 internal HttpRequest (HttpWorkerRequest worker_request, HttpContext context)
139 this.worker_request = worker_request;
140 this.context = context;
143 string [] SplitHeader (int header_index)
145 string [] result = null;
146 string header = worker_request.GetKnownRequestHeader (header_index);
147 if (header != null && header != "" && header.Trim () != "") {
148 result = header.Split (',');
149 for (int i = result.Length - 1; i >= 0; i--)
150 result [i] = result [i].Trim ();
155 public string [] AcceptTypes {
157 if (worker_request == null)
160 if (accept_types == null)
161 accept_types = SplitHeader (HttpWorkerRequest.HeaderAccept);
169 public string AnonymousID {
174 anonymous_id = value;
179 public string ApplicationPath {
181 if (worker_request == null)
183 return worker_request.GetAppPath ();
187 public HttpBrowserCapabilities Browser {
189 if (browser_capabilities == null)
190 browser_capabilities = (HttpBrowserCapabilities)
191 HttpCapabilitiesBase.GetConfigCapabilities (null, this);
193 return browser_capabilities;
197 browser_capabilities = value;
201 public HttpClientCertificate ClientCertificate {
203 if (client_cert == null)
204 client_cert = new HttpClientCertificate (worker_request);
209 static internal string GetParameter (string header, string attr)
211 int ap = header.IndexOf (attr);
216 if (ap >= header.Length)
219 char ending = header [ap];
223 int end = header.IndexOf (ending, ap+1);
225 return (ending == '"') ? null : header.Substring (ap);
227 return header.Substring (ap+1, end-ap-1);
230 public Encoding ContentEncoding {
232 if (encoding == null){
233 if (worker_request == null)
234 throw new HttpException ("No HttpWorkerRequest");
236 string content_type = ContentType;
237 string parameter = GetParameter (content_type, "; charset=");
238 if (parameter == null) {
239 encoding = WebEncoding.RequestEncoding;
242 // Do what the #1 web server does
243 encoding = Encoding.GetEncoding (parameter);
245 encoding = WebEncoding.RequestEncoding;
257 public int ContentLength {
259 if (content_length == -1){
260 if (worker_request == null)
263 string cl = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentLength);
267 content_length = Int32.Parse (cl);
272 // content_length will still be < 0, but we know we gotta read from the client
273 if (content_length < 0)
276 return content_length;
280 public string ContentType {
282 if (content_type == null){
283 if (worker_request != null)
284 content_type = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentType);
286 if (content_type == null)
287 content_type = String.Empty;
294 content_type = value;
298 public HttpCookieCollection Cookies {
300 if (cookies == null) {
301 if (worker_request == null) {
302 cookies = new HttpCookieCollection ();
304 string cookie_hv = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderCookie);
305 cookies = new HttpCookieCollection (cookie_hv);
310 // For J2EE portal support we emulate cookies using the session.
311 GetSessionCookiesForPortal (cookies);
313 if (validate_cookies && !checked_cookies){
314 ValidateCookieCollection (cookies);
315 checked_cookies = true;
323 public string CurrentExecutionFilePath {
325 if (current_exe_path != null)
326 return current_exe_path;
333 public string AppRelativeCurrentExecutionFilePath {
335 return VirtualPathUtility.ToAppRelative (CurrentExecutionFilePath);
340 public string FilePath {
342 if (worker_request == null)
343 return "/"; // required for 2.0
345 if (file_path == null)
346 file_path = UrlUtils.Canonic (worker_request.GetFilePath ());
352 internal string BaseVirtualDir {
354 if (base_virtual_dir == null){
355 base_virtual_dir = FilePath;
356 int p = base_virtual_dir.LastIndexOf ('/');
358 base_virtual_dir = base_virtual_dir.Substring (0, p);
360 return base_virtual_dir;
364 public HttpFileCollection Files {
367 files = new HttpFileCollection ();
368 if ((worker_request != null) && IsContentType ("multipart/form-data", true)) {
369 form = new WebROCollection ();
378 public Stream Filter {
383 if (input_filter == null)
384 input_filter = new InputFilterStream ();
390 // This checks that get_ was called before.
391 if (input_filter == null)
392 throw new HttpException ("Invalid filter");
398 // GetSubStream returns a 'copy' of the InputStream with Position set to 0.
399 static Stream GetSubStream (Stream stream)
402 if (stream is IntPtrStream)
403 return new IntPtrStream (stream);
406 if (stream is MemoryStream) {
407 MemoryStream other = (MemoryStream) stream;
408 return new MemoryStream (other.GetBuffer (), 0, (int) other.Length, false, true);
411 if (stream is TempFileStream) {
412 ((TempFileStream) stream).SavePosition ();
416 throw new NotSupportedException ("The stream is " + stream.GetType ());
419 static void EndSubStream (Stream stream)
421 if (stream is TempFileStream) {
422 ((TempFileStream) stream).RestorePosition ();
427 // Loads the data on the form for multipart/form-data
429 void LoadMultiPart ()
431 string boundary = GetParameter (ContentType, "; boundary=");
432 if (boundary == null)
435 Stream input = GetSubStream (InputStream);
436 HttpMultipart multi_part = new HttpMultipart (input, boundary, ContentEncoding);
438 HttpMultipart.Element e;
439 while ((e = multi_part.ReadNextElement ()) != null) {
440 if (e.Filename == null){
441 byte [] copy = new byte [e.Length];
443 input.Position = e.Start;
444 input.Read (copy, 0, (int) e.Length);
446 form.Add (e.Name, ContentEncoding.GetString (copy));
449 // We use a substream, as in 2.x we will support large uploads streamed to disk,
451 HttpPostedFile sub = new HttpPostedFile (e.Filename, e.ContentType, input, e.Start, e.Length);
452 files.AddFile (e.Name, sub);
455 EndSubStream (input);
459 // Adds the key/value to the form, and sets the argumets to empty
461 void AddRawKeyValue (StringBuilder key, StringBuilder value)
463 form.Add (HttpUtility.UrlDecode (key.ToString (), ContentEncoding),
464 HttpUtility.UrlDecode (value.ToString (), ContentEncoding));
471 // Loads the form data from on a application/x-www-form-urlencoded post
474 void RawLoadWwwForm ()
479 Stream input = GetSubStream (InputStream);
480 StreamReader s = new StreamReader (input, ContentEncoding);
482 StringBuilder key = new StringBuilder ();
483 StringBuilder value = new StringBuilder ();
486 while ((c = s.Read ()) != -1){
489 while ((c = s.Read ()) != -1){
491 AddRawKeyValue (key, value);
494 value.Append ((char) c);
497 AddRawKeyValue (key, value);
501 AddRawKeyValue (key, value);
503 key.Append ((char) c);
506 AddRawKeyValue (key, value);
508 EndSubStream (input);
511 bool IsContentType (string ct, bool starts_with)
514 return StrUtils.StartsWith (ContentType, ct, true);
516 return String.Compare (ContentType, ct, true, CultureInfo.InvariantCulture) == 0;
519 public NameValueCollection Form {
522 form = new WebROCollection ();
523 files = new HttpFileCollection ();
525 if (IsContentType ("application/x-www-form-urlencoded", true))
527 else if (IsContentType ("multipart/form-data", true))
533 if (validate_form && !checked_form){
534 ValidateNameValueCollection ("Form", form);
542 public NameValueCollection Headers {
545 headers = new HeadersCollection (this);
551 public string HttpMethod {
553 if (http_method == null){
554 if (worker_request != null)
555 http_method = worker_request.GetHttpVerbName ();
563 void DoFilter (byte [] buffer)
565 if (input_filter == null || filter == null)
568 if (buffer.Length < 1024)
569 buffer = new byte [1024];
571 // Replace the input with the filtered input
572 input_filter.BaseStream = input_stream;
573 MemoryStream ms = new MemoryStream ();
575 int n = filter.Read (buffer, 0, buffer.Length);
578 ms.Write (buffer, 0, n);
580 // From now on input_stream has the filtered input
581 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
585 const int INPUT_BUFFER_SIZE = 32*1024;
587 TempFileStream GetTempStream ()
589 string tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
590 TempFileStream f = null;
592 Random rnd = new Random ();
597 path = System.IO.Path.Combine (tempdir, "tmp" + num.ToString("x") + ".req");
600 f = new TempFileStream (path);
601 } catch (SecurityException) {
602 // avoid an endless loop
610 void MakeInputStream ()
612 if (input_stream != null)
615 if (worker_request == null) {
616 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
617 DoFilter (new byte [1024]);
622 // Use an unmanaged memory block as this might be a large
625 int content_length = ContentLength;
628 HttpRuntimeSection config = (HttpRuntimeSection) WebConfigurationManager.GetSection ("system.web/httpRuntime");
630 HttpRuntimeConfig config = (HttpRuntimeConfig) HttpContext.GetAppConfig ("system.web/httpRuntime");
632 if ((content_length / 1024) > config.MaxRequestLength)
633 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
637 buffer = worker_request.GetPreloadedEntityBody ();
638 // we check the instance field 'content_length' here, not the local var.
639 if (this.content_length <= 0 || worker_request.IsEntireEntityBodyIsPreloaded ()) {
640 if (buffer == null || content_length == 0) {
641 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
643 input_stream = new MemoryStream (buffer, 0, buffer.Length, false, true);
645 DoFilter (new byte [1024]);
650 total = buffer.Length;
652 if (content_length > 0 && (content_length / 1024) >= config.RequestLengthDiskThreshold) {
653 // Writes the request to disk
654 total = Math.Min (content_length, total);
655 request_file = GetTempStream ();
656 Stream output = request_file;
658 output.Write (buffer, 0, total);
660 if (total < content_length) {
661 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
664 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
665 n = worker_request.ReadEntityBody (buffer, min);
668 output.Write (buffer, 0, n);
670 } while (total < content_length);
673 request_file.SetReadOnly ();
674 input_stream = request_file;
675 } else if (content_length > 0) {
676 // Buffers the request in an IntPtrStream
677 total = Math.Min (content_length, total);
678 IntPtr content = Marshal.AllocHGlobal (content_length);
679 if (content == (IntPtr) 0)
680 throw new HttpException (String.Format ("Not enough memory to allocate {0} bytes.",
684 Marshal.Copy (buffer, 0, content, total);
686 if (total < content_length) {
687 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
690 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
691 n = worker_request.ReadEntityBody (buffer, min);
694 Marshal.Copy (buffer, 0, (IntPtr) ((long)content + total), n);
696 } while (total < content_length);
699 input_stream = new IntPtrStream (content, total);
701 // Buffers the request in a MemoryStream or writes to disk if threshold exceeded
702 MemoryStream ms = new MemoryStream ();
705 ms.Write (buffer, 0, total);
707 buffer = new byte [INPUT_BUFFER_SIZE];
708 long maxlength = config.MaxRequestLength * 1024;
709 long disk_th = config.RequestLengthDiskThreshold * 1024;
712 n = worker_request.ReadEntityBody (buffer, INPUT_BUFFER_SIZE);
716 if (total < 0 || total > maxlength)
717 throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
719 if (ms != null && total > disk_th) {
720 // Swith to on-disk file.
721 request_file = GetTempStream ();
722 ms.WriteTo (request_file);
724 output = request_file;
726 output.Write (buffer, 0, n);
730 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
732 request_file.SetReadOnly ();
733 input_stream = request_file;
738 if (total < content_length)
739 throw new HttpException (411, "The request body is incomplete.");
743 internal void ReleaseResources ()
746 if (input_stream != null){
747 stream = input_stream;
754 if (request_file != null) {
755 stream = request_file;
763 public Stream InputStream {
765 if (input_stream == null)
772 public bool IsAuthenticated {
774 if (context.User == null || context.User.Identity == null)
776 return context.User.Identity.IsAuthenticated;
780 public bool IsSecureConnection {
782 if (worker_request == null)
784 return worker_request.IsSecure ();
788 public string this [string key] {
789 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
791 // "The QueryString, Form, Cookies, or ServerVariables collection member
792 // specified in the key parameter."
793 string val = QueryString [key];
797 HttpCookie cookie = Cookies [key];
802 val = ServerVariables [key];
808 public NameValueCollection Params {
809 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
811 if (all_params == null)
812 all_params = new HttpParamsCollection (QueryString, Form, ServerVariables, Cookies);
820 if (unescaped_path == null)
822 unescaped_path = Uri.UnescapeDataString (UrlComponents.Path);
824 unescaped_path = HttpUtility.UrlDecode (UrlComponents.Path);
826 return unescaped_path;
830 public string PathInfo {
832 if (path_info == null) {
833 if (worker_request == null)
835 path_info = worker_request.GetPathInfo ();
842 public string PhysicalApplicationPath {
844 if (worker_request == null)
845 throw new ArgumentNullException (); // like 2.0, 1.x throws TypeInitializationException
847 string path = HttpRuntime.AppDomainAppPath;
848 if (SecurityManager.SecurityEnabled) {
849 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
855 public string PhysicalPath {
857 if (worker_request == null)
858 return String.Empty; // don't check security with an empty string!
860 if (physical_path == null) {
861 // Don't call HttpRequest.MapPath here, as that one *trims* the input
862 physical_path = worker_request.MapPath (FilePath);
865 if (SecurityManager.SecurityEnabled) {
866 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, physical_path).Demand ();
868 return physical_path;
872 internal string RootVirtualDir {
874 if (root_virtual_dir == null){
875 string fp = FilePath;
876 int p = fp.LastIndexOf ('/');
879 root_virtual_dir = "/";
881 root_virtual_dir = fp.Substring (0, p);
883 return root_virtual_dir;
887 public NameValueCollection QueryString {
889 if (query_string_nvc == null){
890 string q = UrlComponents.Query;
894 query_string_nvc = new WebROCollection ();
895 HttpUtility.ParseQueryString (q, ContentEncoding, query_string_nvc);
896 query_string_nvc.Protect();
899 if (validate_query_string && !checked_query_string) {
900 ValidateNameValueCollection ("QueryString", query_string_nvc);
901 checked_query_string = true;
904 return query_string_nvc;
908 public string RawUrl {
910 if (worker_request != null)
911 return worker_request.GetRawUrl ();
913 return UrlComponents.Path + UrlComponents.Query;
920 public string RequestType {
922 if (request_type == null){
923 if (worker_request != null) {
924 request_type = worker_request.GetHttpVerbName ();
925 http_method = request_type;
927 request_type = "GET";
934 request_type = value;
938 public NameValueCollection ServerVariables {
939 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
941 if (server_variables == null)
942 server_variables = new ServerVariablesCollection (this);
944 return server_variables;
948 public int TotalBytes {
950 Stream ins = InputStream;
951 return (int) ins.Length;
957 if (cached_url == null) {
958 if (orig_url == null)
959 cached_url = UrlComponents.Uri;
961 cached_url = new Uri (orig_url);
968 public Uri UrlReferrer {
970 if (worker_request == null)
973 string hr = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderReferer);
981 public string UserAgent {
983 if (worker_request == null)
986 return worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderUserAgent);
990 public string UserHostAddress {
992 if (worker_request == null)
995 return worker_request.GetRemoteAddress ();
999 public string UserHostName {
1001 if (worker_request == null)
1004 return worker_request.GetRemoteName ();
1008 public string [] UserLanguages {
1010 if (worker_request == null)
1013 if (user_languages == null)
1014 user_languages = SplitHeader (HttpWorkerRequest.HeaderAcceptLanguage);
1016 return user_languages;
1020 public byte [] BinaryRead (int count)
1023 throw new ArgumentException ("count is < 0");
1025 Stream s = InputStream;
1026 byte [] ret = new byte [count];
1027 if (s.Read (ret, 0, count) != count)
1028 throw new ArgumentException (
1029 String.Format ("count {0} exceeds length of available input {1}",
1030 count, s.Length - s.Position));
1034 public int [] MapImageCoordinates (string imageFieldName)
1036 string method = HttpMethod;
1037 NameValueCollection coll = null;
1038 if (method == "HEAD" || method == "GET")
1040 else if (method == "POST")
1046 string x = coll [imageFieldName + ".x"];
1047 if (x == null || x == "")
1050 string y = coll [imageFieldName + ".y"];
1051 if (y == null || y == "")
1054 int [] result = new int [2];
1056 result [0] = Int32.Parse (x);
1057 result [1] = Int32.Parse (y);
1065 public string MapPath (string virtualPath)
1067 if (worker_request == null)
1070 return MapPath (virtualPath, BaseVirtualDir, true);
1073 public string MapPath (string virtualPath, string baseVirtualDir, bool allowCrossAppMapping)
1075 if (worker_request == null)
1076 throw new HttpException ("No HttpWorkerRequest");
1078 if (virtualPath == null)
1081 virtualPath = virtualPath.Trim ();
1082 if (virtualPath.Length == 0)
1086 if (virtualPath.IndexOf (':') != -1)
1087 throw new HttpException (String.Format ("'{0}' is not a valid virtual path.", virtualPath));
1089 string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
1091 if (!VirtualPathUtility.IsRooted (virtualPath)) {
1092 if (StrUtils.IsNullOrEmpty (baseVirtualDir))
1093 baseVirtualDir = appVirtualPath;
1094 virtualPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (baseVirtualDir), virtualPath);
1096 virtualPath = VirtualPathUtility.ToAbsolute (virtualPath);
1098 if (!allowCrossAppMapping){
1099 if (!StrUtils.StartsWith (virtualPath, appVirtualPath, true))
1100 throw new HttpException ("MapPath: Mapping across applications not allowed");
1101 if (appVirtualPath.Length > 1 && virtualPath.Length > 1 && virtualPath [0] != '/')
1102 throw new HttpException ("MapPath: Mapping across applications not allowed");
1105 return worker_request.MapPath (virtualPath);
1107 string path = worker_request.MapPath (virtualPath);
1108 if (virtualPath [virtualPath.Length - 1] != '/' && path [path.Length - 1] == System.IO.Path.DirectorySeparatorChar)
1109 path = path.TrimEnd (System.IO.Path.DirectorySeparatorChar);
1114 public void SaveAs (string filename, bool includeHeaders)
1116 Stream output = new FileStream (filename, FileMode.Create);
1117 if (includeHeaders) {
1118 StringBuilder sb = new StringBuilder ();
1119 string version = String.Empty;
1121 if (worker_request != null) {
1122 version = worker_request.GetHttpVersion ();
1123 path = UrlComponents.Path;
1125 string qs = UrlComponents.Query;
1127 sb.AppendFormat ("{0} {1}{2} {3}\r\n", HttpMethod, path, qs, version);
1128 NameValueCollection coll = Headers;
1129 foreach (string k in coll.AllKeys) {
1132 sb.Append (coll [k]);
1137 byte [] bytes = Encoding.GetEncoding (28591).GetBytes (sb.ToString ());
1138 output.Write (bytes, 0, bytes.Length);
1141 // More than 1 call to SaveAs works fine on MS, so we "copy" the stream
1142 // to keep InputStream in its state.
1143 Stream input = GetSubStream (InputStream);
1145 long len = input.Length;
1146 int buf_size = (int) Math.Min ((len < 0 ? 0 : len), 8192);
1147 byte [] data = new byte [buf_size];
1149 while (len > 0 && (count = input.Read (data, 0, buf_size)) > 0) {
1150 output.Write (data, 0, count);
1156 EndSubStream (input);
1160 public void ValidateInput ()
1162 validate_cookies = true;
1163 validate_query_string = true;
1164 validate_form = true;
1167 #region internal routines
1168 internal string ClientTarget {
1170 return client_target;
1174 client_target = value;
1185 string address = worker_request.GetRemoteAddress ();
1187 if (StrUtils.IsNullOrEmpty (address))
1190 if (address == "127.0.0.1")
1193 System.Net.IPAddress remoteAddr = System.Net.IPAddress.Parse (address);
1194 if (System.Net.IPAddress.IsLoopback (remoteAddr))
1197 for (int i = 0; i < host_addresses.Length; i++)
1198 if (remoteAddr.Equals (host_addresses [i]))
1205 internal void SetFilePath (string path)
1208 physical_path = null;
1211 internal void SetCurrentExePath (string path)
1214 current_exe_path = path;
1216 UrlComponents.Path = path;
1217 // recreated on demand
1218 root_virtual_dir = null;
1219 base_virtual_dir = null;
1220 physical_path = null;
1221 unescaped_path = null;
1224 internal void SetPathInfo (string pi)
1230 // Headers is ReadOnly, so we need this hack for cookie-less sessions.
1231 internal void SetHeader (string name, string value)
1233 WebROCollection h = (WebROCollection) Headers;
1239 // Notice: there is nothing raw about this querystring.
1240 internal string QueryStringRaw {
1242 return UrlComponents.Query;
1246 UrlComponents.Query = value;
1248 query_string_nvc = null;
1252 // Internal, dont know what it does, so flagged as public so we can see it.
1253 internal void SetForm (WebROCollection coll)
1258 internal HttpWorkerRequest WorkerRequest {
1260 return worker_request;
1264 internal HttpContext Context {
1270 static void ValidateNameValueCollection (string name, NameValueCollection coll)
1275 foreach (string key in coll.Keys) {
1276 string val = coll [key];
1277 if (val != null && val != "" && CheckString (val))
1278 ThrowValidationException (name, key, val);
1282 static void ValidateCookieCollection (HttpCookieCollection cookies)
1284 if (cookies == null)
1287 int size = cookies.Count;
1289 for (int i = 0 ; i < size ; i++) {
1290 cookie = cookies[i];
1291 string value = cookie.Value;
1293 if (value != null && value != "" && CheckString (value))
1294 ThrowValidationException ("Cookies", cookie.Name, cookie.Value);
1298 static void ThrowValidationException (string name, string key, string value)
1300 string v = "\"" + value + "\"";
1302 v = v.Substring (0, 16) + "...\"";
1304 string msg = String.Format ("A potentially dangerous Request.{0} value was " +
1305 "detected from the client ({1}={2}).", name, key, v);
1307 throw new HttpRequestValidationException (msg);
1310 static bool CheckString (string val)
1312 int len = val.Length;
1316 char current = val [0];
1317 for (int idx = 1; idx < len; idx++) {
1318 char next = val [idx];
1319 if (current == '<' || current == '\xff1c') {
1320 if (next == '!' || next < ' '
1321 || (next >= 'a' && next <= 'z')
1322 || (next >= 'A' && next <= 'Z'))
1324 } else if (current == '&' && next == '#') {
1334 static System.Net.IPAddress [] GetLocalHostAddresses ()
1337 string hostName = System.Net.Dns.GetHostName ();
1339 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostAddresses (hostName);
1341 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostByName (hostName).AddressList;
1347 return new System.Net.IPAddress[0];
1353 #region Helper classes
1356 // Stream-based multipart handling.
1358 // In this incarnation deals with an HttpInputStream as we are now using
1359 // IntPtr-based streams instead of byte []. In the future, we will also
1360 // send uploads above a certain threshold into the disk (to implement
1361 // limit-less HttpInputFiles).
1364 class HttpMultipart {
1366 public class Element {
1367 public string ContentType;
1369 public string Filename;
1373 public override string ToString ()
1375 return string.Format ("ContentType {0}, Name {1}, Filename {2}, Start {3}, Length {4}",
1376 ContentType, Name, Filename, Start, Length);
1382 byte [] boundary_bytes;
1388 const byte HYPHEN = (byte) '-', LF = (byte) '\n', CR = (byte) '\r';
1391 // In the case of multipart entities, in which one or more different
1392 // sets of data are combined in a single body, a "multipart" media type
1393 // field must appear in the entity's header. The body must then contain
1394 // one or more body parts, each preceded by a boundary delimiter line,
1395 // and the last one followed by a closing boundary delimiter line.
1396 // After its boundary delimiter line, each body part then consists of a
1397 // header area, a blank line, and a body area. Thus a body part is
1398 // similar to an RFC 822 message in syntax, but different in meaning.
1400 public HttpMultipart (Stream data, string b, Encoding encoding)
1404 boundary_bytes = encoding.GetBytes (b);
1405 buffer = new byte [boundary_bytes.Length + 2]; // CRLF or '--'
1406 this.encoding = encoding;
1407 sb = new StringBuilder ();
1412 // CRLF or LF are ok as line endings.
1413 bool got_cr = false;
1417 b = data.ReadByte ();
1426 sb.Append ((char) b);
1432 return sb.ToString ();
1436 static string GetContentDispositionAttribute (string l, string name)
1438 int idx = l.IndexOf (name + "=\"");
1441 int begin = idx + name.Length + "=\"".Length;
1442 int end = l.IndexOf ('"', begin);
1447 return l.Substring (begin, end - begin);
1450 string GetContentDispositionAttributeWithEncoding (string l, string name)
1452 int idx = l.IndexOf (name + "=\"");
1455 int begin = idx + name.Length + "=\"".Length;
1456 int end = l.IndexOf ('"', begin);
1462 string temp = l.Substring (begin, end - begin);
1463 byte [] source = new byte [temp.Length];
1464 for (int i = temp.Length - 1; i >= 0; i--)
1465 source [i] = (byte) temp [i];
1467 return encoding.GetString (source);
1470 bool ReadBoundary ()
1473 string line = ReadLine ();
1476 if (line [0] != '-' || line [1] != '-')
1479 if (!StrUtils.EndsWith (line, boundary, false))
1487 string ReadHeaders ()
1489 string s = ReadLine ();
1496 bool CompareBytes (byte [] orig, byte [] other)
1498 for (int i = orig.Length - 1; i >= 0; i--)
1499 if (orig [i] != other [i])
1505 long MoveToNextBoundary ()
1508 bool got_cr = false;
1511 int c = data.ReadByte ();
1516 if (state == 0 && c == LF) {
1517 retval = data.Position - 1;
1521 c = data.ReadByte ();
1522 } else if (state == 0) {
1524 c = data.ReadByte ();
1525 } else if (state == 1 && c == '-') {
1526 c = data.ReadByte ();
1533 continue; // no ReadByte() here
1536 int nread = data.Read (buffer, 0, buffer.Length);
1537 int bl = buffer.Length;
1541 if (!CompareBytes (boundary_bytes, buffer)) {
1543 data.Position = retval + 2;
1548 c = data.ReadByte ();
1552 if (buffer [bl - 2] == '-' && buffer [bl - 1] == '-') {
1554 } else if (buffer [bl - 2] != CR || buffer [bl - 1] != LF) {
1556 data.Position = retval + 2;
1561 c = data.ReadByte ();
1564 data.Position = retval + 2;
1570 state = 0; // no ReadByte() here
1577 public Element ReadNextElement ()
1579 if (at_eof || ReadBoundary ())
1582 Element elem = new Element ();
1584 while ((header = ReadHeaders ()) != null) {
1585 if (StrUtils.StartsWith (header, "Content-Disposition:", true)) {
1586 elem.Name = GetContentDispositionAttribute (header, "name");
1587 elem.Filename = GetContentDispositionAttributeWithEncoding (header, "filename");
1588 } else if (StrUtils.StartsWith (header, "Content-Type:", true)) {
1589 elem.ContentType = header.Substring ("Content-Type:".Length).Trim ();
1593 long start = data.Position;
1595 long pos = MoveToNextBoundary ();
1599 elem.Length = pos - start;