2 // System.Web.HttpRequest.cs
6 // Miguel de Icaza (miguel@novell.com)
7 // Gonzalo Paniagua Javier (gonzalo@novell.com)
8 // Marek Habersack <mhabersack@novell.com>
12 // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
13 // Copyright (C) 2011-2012 Xamarin, Inc (http://xamarin.com)
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Collections;
36 using System.Collections.Specialized;
38 using System.Runtime.InteropServices;
39 using System.Security;
40 using System.Security.Permissions;
41 using System.Security.Principal;
42 using System.Web.Configuration;
43 using System.Web.Management;
45 using System.Web.Util;
46 using System.Globalization;
49 using System.Security.Authentication.ExtendedProtection;
50 using System.Web.Routing;
55 // CAS - no InheritanceDemand here as the class is sealed
56 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
57 public sealed partial class HttpRequest
59 HttpWorkerRequest worker_request;
61 WebROCollection query_string_nvc;
65 string orig_url = null;
66 UriBuilder url_components;
71 // On-demand computed values
73 HttpBrowserCapabilities browser_capabilities;
74 string file_path, base_virtual_dir, root_virtual_dir, client_file_path;
76 int content_length = -1;
78 string current_exe_path;
80 string unescaped_path;
84 WebROCollection all_params;
85 WebROCollection headers;
87 InputFilterStream input_filter;
89 HttpCookieCollection cookies;
93 HttpFileCollection files;
95 ServerVariablesCollection server_variables;
96 HttpClientCertificate client_cert;
99 string [] accept_types;
100 string [] user_languages;
102 TempFileStream request_file;
104 readonly static System.Net.IPAddress [] host_addresses;
107 bool validate_cookies, validate_query_string, validate_form;
108 bool checked_cookies, checked_query_string, checked_form;
109 static readonly UrlMappingCollection urlMappings;
110 readonly static char [] queryTrimChars = {'?'};
112 bool lazyFormValidation;
113 bool lazyQueryStringValidation;
114 bool inputValidationEnabled;
115 RequestContext requestContext;
116 BufferlessInputStream bufferlessInputStream;
118 static bool validateRequestNewMode;
119 internal static bool ValidateRequestNewMode {
120 get { return validateRequestNewMode; }
123 internal bool InputValidationEnabled {
124 get { return inputValidationEnabled; }
127 private static char[] RequestPathInvalidCharacters {
131 private static char[] CharsFromList (string list)
133 // List format is very strict and enforced by the Configuration
134 // there must be a single char separated by commas with no trailing comma
135 // whitespace is allowed though and should be trimmed.
137 string [] pieces = list.Split (',');
139 char [] chars = new char [pieces.Length];
140 for (int i = 0; i < chars.Length; i++) {
141 string trimmed = pieces [i].Trim ();
142 if (trimmed.Length != 1) {
143 // This should have been caught by System.Web.Configuration
144 // and throw a configuration error. This is just here for sanity
145 throw new System.Configuration.ConfigurationErrorsException ();
148 chars [i] = trimmed [0];
155 static HttpRequest ()
158 UrlMappingsSection ums = WebConfigurationManager.GetWebApplicationSection ("system.web/urlMappings") as UrlMappingsSection;
159 if (ums != null && ums.IsEnabled) {
160 urlMappings = ums.UrlMappings;
161 if (urlMappings.Count == 0)
166 Version validationMode = HttpRuntime.Section.RequestValidationMode;
168 if (validationMode >= new Version (4, 0)) {
169 validateRequestNewMode = true;
170 string invalidChars = HttpRuntime.Section.RequestPathInvalidCharacters;
171 if (!String.IsNullOrEmpty (invalidChars))
172 RequestPathInvalidCharacters = CharsFromList (invalidChars);
176 // unlikely to happen
179 host_addresses = GetLocalHostAddresses ();
182 public HttpRequest (string filename, string url, string queryString)
184 // warning 169: what are we supposed to do with filename?
186 //this.filename = filename;
189 url_components = new UriBuilder (url);
190 url_components.Query = queryString;
192 query_string_nvc = new WebROCollection ();
193 if (queryString != null)
194 HttpUtility.ParseQueryString (queryString, Encoding.Default, query_string_nvc);
195 query_string_nvc.Protect ();
198 internal HttpRequest (HttpWorkerRequest worker_request, HttpContext context)
200 this.worker_request = worker_request;
201 this.context = context;
204 internal UriBuilder UrlComponents {
206 if (url_components == null) {
208 byte[] queryStringRaw = worker_request.GetQueryStringRawBytes();
209 if(queryStringRaw != null)
210 query = ContentEncoding.GetString(queryStringRaw);
212 query = worker_request.GetQueryString();
214 BuildUrlComponents (ApplyUrlMapping (worker_request.GetUriPath ()), query);
216 return url_components;
220 void BuildUrlComponents (string path, string query)
222 if (url_components != null)
224 url_components = new UriBuilder ();
225 url_components.Scheme = worker_request.GetProtocol ();
226 url_components.Host = worker_request.GetServerName ();
227 url_components.Port = worker_request.GetLocalPort ();
228 url_components.Path = path;
229 if (query != null && query.Length > 0)
230 url_components.Query = query.TrimStart (queryTrimChars);
233 internal string ApplyUrlMapping (string url)
235 if (urlMappings == null)
238 string relUrl = VirtualPathUtility.ToAppRelative (url);
239 UrlMapping um = null;
241 foreach (UrlMapping u in urlMappings) {
244 if (String.Compare (relUrl, u.Url, StringComparison.Ordinal) == 0) {
253 string rawUrl = VirtualPathUtility.ToAbsolute (um.MappedUrl.Trim ());
254 Uri newUrl = new Uri ("http://host.com" + rawUrl);
256 if (url_components != null) {
257 url_components.Path = newUrl.AbsolutePath;
258 url_components.Query = newUrl.Query.TrimStart (queryTrimChars);
259 query_string_nvc = new WebROCollection ();
260 HttpUtility.ParseQueryString (newUrl.Query, Encoding.Default, query_string_nvc);
261 query_string_nvc.Protect ();
263 BuildUrlComponents (newUrl.AbsolutePath, newUrl.Query);
265 return url_components.Path;
268 string [] SplitHeader (int header_index)
270 string [] result = null;
271 string header = worker_request.GetKnownRequestHeader (header_index);
272 if (header != null && header != "" && header.Trim () != "") {
273 result = header.Split (',');
274 for (int i = result.Length - 1; i >= 0; i--)
275 result [i] = result [i].Trim ();
280 public string [] AcceptTypes {
282 if (worker_request == null)
285 if (accept_types == null)
286 accept_types = SplitHeader (HttpWorkerRequest.HeaderAccept);
292 public WindowsIdentity LogonUserIdentity {
293 get { throw new NotImplementedException (); }
297 public string AnonymousID {
302 anonymous_id = value;
306 public string ApplicationPath {
308 if (worker_request == null)
310 return worker_request.GetAppPath ();
314 public HttpBrowserCapabilities Browser {
316 if (browser_capabilities == null)
318 browser_capabilities = HttpCapabilitiesBase.BrowserCapabilitiesProvider.GetBrowserCapabilities (this);
320 browser_capabilities = (HttpBrowserCapabilities)
321 HttpCapabilitiesBase.GetConfigCapabilities (null, this);
324 return browser_capabilities;
328 browser_capabilities = value;
332 internal bool BrowserMightHaveSpecialWriter {
334 return (browser_capabilities != null
335 || HttpApplicationFactory.AppBrowsersFiles.Length > 0);
339 internal bool BrowserMightHaveAdapters {
341 return (browser_capabilities != null
342 || HttpApplicationFactory.AppBrowsersFiles.Length > 0);
346 public HttpClientCertificate ClientCertificate {
348 if (client_cert == null)
349 client_cert = new HttpClientCertificate (worker_request);
354 static internal string GetParameter (string header, string attr)
356 int ap = header.IndexOf (attr);
361 if (ap >= header.Length)
364 char ending = header [ap];
368 int end = header.IndexOf (ending, ap+1);
370 return (ending == '"') ? null : header.Substring (ap);
372 return header.Substring (ap+1, end-ap-1);
375 public Encoding ContentEncoding {
377 if (encoding == null){
378 if (worker_request == null)
379 throw HttpException.NewWithCode ("No HttpWorkerRequest", WebEventCodes.RuntimeErrorRequestAbort);
381 string content_type = ContentType;
382 string parameter = GetParameter (content_type, "; charset=");
383 if (parameter == null) {
384 encoding = WebEncoding.RequestEncoding;
387 // Do what the #1 web server does
388 encoding = Encoding.GetEncoding (parameter);
390 encoding = WebEncoding.RequestEncoding;
402 public int ContentLength {
404 if (content_length == -1){
405 if (worker_request == null)
408 string cl = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentLength);
412 content_length = Int32.Parse (cl);
417 // content_length will still be < 0, but we know we gotta read from the client
418 if (content_length < 0)
421 return content_length;
425 public string ContentType {
427 if (content_type == null){
428 if (worker_request != null)
429 content_type = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderContentType);
431 if (content_type == null)
432 content_type = String.Empty;
439 content_type = value;
443 public HttpCookieCollection Cookies {
445 if (cookies == null) {
446 if (worker_request == null) {
447 cookies = new HttpCookieCollection ();
449 string cookie_hv = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderCookie);
450 cookies = new HttpCookieCollection (cookie_hv);
455 // For J2EE portal support we emulate cookies using the session.
456 GetSessionCookiesForPortal (cookies);
458 bool needValidation = validate_cookies;
460 needValidation |= validateRequestNewMode;
462 if (needValidation && !checked_cookies) {
463 // Setting this before calling the validator prevents
464 // possible endless recursion
465 checked_cookies = true;
466 ValidateCookieCollection (cookies);
474 public string CurrentExecutionFilePath {
476 if (current_exe_path != null)
477 return current_exe_path;
483 public string CurrentExecutionFilePathExtension {
484 get { return global::System.IO.Path.GetExtension (CurrentExecutionFilePath); }
487 public string AppRelativeCurrentExecutionFilePath {
489 return VirtualPathUtility.ToAppRelative (CurrentExecutionFilePath);
493 public string FilePath {
495 if (worker_request == null)
496 return "/"; // required for 2.0
498 if (file_path == null)
499 file_path = UrlUtils.Canonic (ApplyUrlMapping (worker_request.GetFilePath ()));
505 internal string ClientFilePath {
507 if (client_file_path == null) {
508 if (worker_request == null)
511 return UrlUtils.Canonic (ApplyUrlMapping (worker_request.GetFilePath ()));
514 return client_file_path;
518 if (value == null || value.Length == 0)
519 client_file_path = null;
521 client_file_path = value;
525 internal string BaseVirtualDir {
527 if (base_virtual_dir == null){
528 base_virtual_dir = FilePath;
529 if (UrlUtils.HasSessionId (base_virtual_dir))
530 base_virtual_dir = UrlUtils.RemoveSessionId (VirtualPathUtility.GetDirectory (base_virtual_dir), base_virtual_dir);
532 int p = base_virtual_dir.LastIndexOf ('/');
536 base_virtual_dir = base_virtual_dir.Substring (0, p);
538 base_virtual_dir = "/";
540 return base_virtual_dir;
544 public HttpFileCollection Files {
547 files = new HttpFileCollection ();
548 if ((worker_request != null) && IsContentType ("multipart/form-data", true)) {
549 form = new WebROCollection ();
558 public Stream Filter {
563 if (input_filter == null)
564 input_filter = new InputFilterStream ();
570 // This checks that get_ was called before.
571 if (input_filter == null)
572 throw new HttpException ("Invalid filter");
578 // GetSubStream returns a 'copy' of the InputStream with Position set to 0.
579 static Stream GetSubStream (Stream stream)
581 if (stream is IntPtrStream)
582 return new IntPtrStream (stream);
584 if (stream is MemoryStream) {
585 MemoryStream other = (MemoryStream) stream;
586 return new MemoryStream (other.GetBuffer (), 0, (int) other.Length, false, true);
589 if (stream is TempFileStream) {
590 ((TempFileStream) stream).SavePosition ();
594 throw new NotSupportedException ("The stream is " + stream.GetType ());
597 static void EndSubStream (Stream stream)
599 if (stream is TempFileStream) {
600 ((TempFileStream) stream).RestorePosition ();
605 // Loads the data on the form for multipart/form-data
607 void LoadMultiPart ()
609 string boundary = GetParameter (ContentType, "; boundary=");
610 if (boundary == null)
613 Stream input = GetSubStream (InputStream);
614 HttpMultipart multi_part = new HttpMultipart (input, boundary, ContentEncoding);
616 HttpMultipart.Element e;
617 while ((e = multi_part.ReadNextElement ()) != null) {
618 if (e.Filename == null){
619 byte [] copy = new byte [e.Length];
621 input.Position = e.Start;
622 input.Read (copy, 0, (int) e.Length);
624 form.Add (e.Name, ContentEncoding.GetString (copy));
627 // We use a substream, as in 2.x we will support large uploads streamed to disk,
629 HttpPostedFile sub = new HttpPostedFile (e.Filename, e.ContentType, input, e.Start, e.Length);
630 files.AddFile (e.Name, sub);
633 EndSubStream (input);
637 // Adds the key/value to the form, and sets the argumets to empty
639 void AddRawKeyValue (StringBuilder key, StringBuilder value)
641 string decodedKey = HttpUtility.UrlDecode (key.ToString (), ContentEncoding);
642 form.Add (decodedKey,
643 HttpUtility.UrlDecode (value.ToString (), ContentEncoding));
650 // Loads the form data from on a application/x-www-form-urlencoded post
653 void RawLoadWwwForm ()
658 using (Stream input = GetSubStream (InputStream)) {
659 using (StreamReader s = new StreamReader (input, ContentEncoding)) {
660 StringBuilder key = new StringBuilder ();
661 StringBuilder value = new StringBuilder ();
664 while ((c = s.Read ()) != -1){
667 while ((c = s.Read ()) != -1){
669 AddRawKeyValue (key, value);
672 value.Append ((char) c);
675 AddRawKeyValue (key, value);
679 AddRawKeyValue (key, value);
681 key.Append ((char) c);
684 AddRawKeyValue (key, value);
686 EndSubStream (input);
691 bool IsContentType (string ct, bool starts_with)
694 return StrUtils.StartsWith (ContentType, ct, true);
696 return String.Compare (ContentType, ct, true, Helpers.InvariantCulture) == 0;
699 internal WebROCollection FormUnvalidated {
702 form = new WebROCollection ();
703 files = new HttpFileCollection ();
705 if (IsContentType ("multipart/form-data", true))
708 IsContentType ("application/x-www-form-urlencoded", true))
718 public NameValueCollection Form {
720 NameValueCollection form = FormUnvalidated;
722 if (validateRequestNewMode && !checked_form) {
723 if (!lazyFormValidation) {
724 // Setting this before calling the validator prevents
725 // possible endless recursion
727 ValidateNameValueCollection ("Form", form, RequestValidationSource.Form);
731 if (validate_form && !checked_form){
733 ValidateNameValueCollection ("Form", form);
740 public NameValueCollection Headers {
742 if (headers == null) {
743 headers = new HeadersCollection (this);
745 if (validateRequestNewMode) {
746 RequestValidator validator = RequestValidator.Current;
747 int validationFailureIndex;
749 foreach (string hkey in headers.AllKeys) {
750 string value = headers [hkey];
752 if (!validator.IsValidRequestString (HttpContext.Current, value, RequestValidationSource.Headers, hkey, out validationFailureIndex))
753 ThrowValidationException ("Headers", hkey, value);
763 public string HttpMethod {
765 if (http_method == null){
766 if (worker_request != null)
767 http_method = worker_request.GetHttpVerbName ();
775 void DoFilter (byte [] buffer)
777 if (input_filter == null || filter == null)
780 if (buffer.Length < 1024)
781 buffer = new byte [1024];
783 // Replace the input with the filtered input
784 input_filter.BaseStream = input_stream;
785 MemoryStream ms = new MemoryStream ();
787 int n = filter.Read (buffer, 0, buffer.Length);
790 ms.Write (buffer, 0, n);
792 // From now on input_stream has the filtered input
793 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
796 const int INPUT_BUFFER_SIZE = 32*1024;
798 TempFileStream GetTempStream ()
800 string tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
801 TempFileStream f = null;
803 Random rnd = new Random ();
808 path = System.IO.Path.Combine (tempdir, "tmp" + num.ToString("x") + ".req");
811 f = new TempFileStream (path);
812 } catch (SecurityException) {
813 // avoid an endless loop
821 void MakeInputStream ()
823 if (input_stream != null)
826 if (worker_request == null) {
827 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
828 DoFilter (new byte [1024]);
833 // Use an unmanaged memory block as this might be a large
836 int content_length = ContentLength;
837 int content_length_kb = content_length / 1024;
838 HttpRuntimeSection config = HttpRuntime.Section;
839 if (content_length_kb > config.MaxRequestLength)
840 throw HttpException.NewWithCode (400, "Upload size exceeds httpRuntime limit.", WebEventCodes.RuntimeErrorPostTooLarge);
844 buffer = worker_request.GetPreloadedEntityBody ();
845 // we check the instance field 'content_length' here, not the local var.
846 if (this.content_length <= 0 || worker_request.IsEntireEntityBodyIsPreloaded ()) {
847 if (buffer == null || content_length == 0) {
848 input_stream = new MemoryStream (new byte [0], 0, 0, false, true);
850 input_stream = new MemoryStream (buffer, 0, buffer.Length, false, true);
852 DoFilter (new byte [1024]);
857 total = buffer.Length;
859 if (content_length > 0 && content_length_kb >= config.RequestLengthDiskThreshold) {
860 // Writes the request to disk
861 total = Math.Min (content_length, total);
862 request_file = GetTempStream ();
863 Stream output = request_file;
865 output.Write (buffer, 0, total);
867 if (total < content_length) {
868 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
871 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
872 n = worker_request.ReadEntityBody (buffer, min);
875 output.Write (buffer, 0, n);
877 } while (total < content_length);
880 request_file.SetReadOnly ();
881 input_stream = request_file;
882 } else if (content_length > 0) {
883 // Buffers the request in an IntPtrStream
884 total = Math.Min (content_length, total);
885 IntPtr content = Marshal.AllocHGlobal (content_length);
886 if (content == (IntPtr) 0)
887 throw HttpException.NewWithCode (
888 String.Format ("Not enough memory to allocate {0} bytes.", content_length),
889 WebEventCodes.WebErrorOtherError);
892 Marshal.Copy (buffer, 0, content, total);
894 if (total < content_length) {
895 buffer = new byte [Math.Min (content_length, INPUT_BUFFER_SIZE)];
898 int min = Math.Min (content_length - total, INPUT_BUFFER_SIZE);
899 n = worker_request.ReadEntityBody (buffer, min);
902 Marshal.Copy (buffer, 0, (IntPtr) ((long)content + total), n);
904 } while (total < content_length);
907 input_stream = new IntPtrStream (content, total);
909 // Buffers the request in a MemoryStream or writes to disk if threshold exceeded
910 MemoryStream ms = new MemoryStream ();
913 ms.Write (buffer, 0, total);
915 buffer = new byte [INPUT_BUFFER_SIZE];
916 long maxlength = config.MaxRequestLength * 1024L;
917 long disk_th = config.RequestLengthDiskThreshold * 1024L;
920 n = worker_request.ReadEntityBody (buffer, INPUT_BUFFER_SIZE);
924 if (total < 0 || total > maxlength)
925 throw HttpException.NewWithCode (400, "Upload size exceeds httpRuntime limit.", WebEventCodes.RuntimeErrorPostTooLarge);
927 if (ms != null && total > disk_th) {
928 // Swith to on-disk file.
929 request_file = GetTempStream ();
930 ms.WriteTo (request_file);
932 output = request_file;
934 output.Write (buffer, 0, n);
938 input_stream = new MemoryStream (ms.GetBuffer (), 0, (int) ms.Length, false, true);
940 request_file.SetReadOnly ();
941 input_stream = request_file;
946 if (total < content_length)
947 throw HttpException.NewWithCode (411, "The request body is incomplete.", WebEventCodes.WebErrorOtherError);
950 internal void ReleaseResources ()
953 if (input_stream != null){
954 stream = input_stream;
961 if (request_file != null) {
962 stream = request_file;
970 public RequestContext RequestContext {
972 if (requestContext == null)
973 requestContext = new RequestContext (new HttpContextWrapper (this.context ?? HttpContext.Current), new RouteData ());
975 return requestContext;
978 internal set { requestContext = value; }
981 public ChannelBinding HttpChannelBinding {
983 throw new PlatformNotSupportedException ("This property is not supported.");
987 public Stream GetBufferlessInputStream ()
989 if (bufferlessInputStream == null) {
990 if (input_stream != null)
991 throw new HttpException ("Input stream has already been created");
993 // we don't need to hook up the filter here, because the raw stream should be returned
994 bufferlessInputStream = new BufferlessInputStream (this);
997 return bufferlessInputStream;
1001 // Stream that returns the data as it is read, without buffering
1003 class BufferlessInputStream : Stream {
1004 HttpRequest request;
1006 // cached, the request content-length
1009 // buffer that holds preloaded data
1010 byte [] preloadedBuffer;
1012 // indicates if we already served the whole preloaded buffer
1013 bool preloaded_served;
1015 // indicates if we already checked the request content-length against httpRuntime limit
1016 bool checked_maxRequestLength;
1018 // our stream position
1022 // @request: the containing request that created us, used to find out content length
1023 public BufferlessInputStream (HttpRequest request)
1025 this.request = request;
1026 content_length = request.ContentLength;
1029 public override bool CanRead {
1030 get { return true; }
1033 public override bool CanSeek {
1034 get { return false; }
1037 public override bool CanWrite {
1038 get { return false; }
1041 public override long Length {
1043 return content_length;
1047 public override long Position {
1052 throw new NotSupportedException ("This is a readonly stream");
1056 public override void Flush ()
1060 public override int Read (byte [] buffer, int offset, int count)
1063 throw new ArgumentNullException ("buffer");
1065 if (offset < 0 || count < 0)
1066 throw new ArgumentOutOfRangeException ("offset or count less than zero.");
1068 if (buffer.Length - offset < count )
1069 throw new ArgumentException ("offset+count",
1070 "The size of the buffer is less than offset + count.");
1072 if (count == 0 || request.worker_request == null)
1075 if (!checked_maxRequestLength) {
1076 int content_length_kb = content_length / 1024;
1077 HttpRuntimeSection config = HttpRuntime.Section;
1078 if (content_length_kb > config.MaxRequestLength)
1079 throw HttpException.NewWithCode (400, "Upload size exceeds httpRuntime limit.", WebEventCodes.RuntimeErrorPostTooLarge);
1081 checked_maxRequestLength = true;
1084 // Serve the bytes we might have preloaded already.
1085 if (!preloaded_served) {
1086 if (preloadedBuffer == null)
1087 preloadedBuffer = request.worker_request.GetPreloadedEntityBody ();
1089 if (preloadedBuffer != null) {
1090 long bytes_left = preloadedBuffer.Length-position;
1091 int n = (int) Math.Min (count, bytes_left);
1092 Array.Copy (preloadedBuffer, position, buffer, offset, n);
1095 if (n == bytes_left)
1096 preloaded_served = true;
1101 preloaded_served = true;
1104 // serve bytes from worker request if available
1105 if (position < content_length) {
1106 long bytes_left = content_length-position;
1109 if (bytes_left < count)
1110 n = (int) bytes_left;
1112 int bytes_read = request.worker_request.ReadEntityBody (buffer, offset, n);
1113 position += bytes_read;
1120 public override long Seek (long offset, SeekOrigin origin)
1122 throw new NotSupportedException ("Can not seek on the HttpRequest.BufferlessInputStream");
1125 public override void SetLength (long value)
1127 throw new NotSupportedException ("Can not set length on the HttpRequest.BufferlessInputStream");
1130 public override void Write (byte [] buffer, int offset, int count)
1132 throw new NotSupportedException ("Can not write on the HttpRequest.BufferlessInputStream");
1136 // TODO: explicitly support the async methods if there is a convenient way of doing it
1140 public Stream InputStream {
1142 if (input_stream == null)
1145 return input_stream;
1149 public bool IsAuthenticated {
1151 if (context.User == null || context.User.Identity == null)
1153 return context.User.Identity.IsAuthenticated;
1157 public bool IsSecureConnection {
1159 if (worker_request == null)
1161 return worker_request.IsSecure ();
1165 public string this [string key] {
1166 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
1168 // "The QueryString, Form, Cookies, or ServerVariables collection member
1169 // specified in the key parameter."
1170 string val = QueryString [key];
1174 HttpCookie cookie = Cookies [key];
1179 val = ServerVariables [key];
1185 public NameValueCollection Params {
1186 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
1188 if (all_params == null)
1189 all_params = new HttpParamsCollection (QueryString, Form, ServerVariables, Cookies);
1195 internal string PathNoValidation {
1197 if (original_path == null) {
1198 if (url_components != null)
1199 // use only if it's already been instantiated, so that we can't go into endless
1200 // recursion in some scenarios
1201 original_path = UrlComponents.Path;
1203 original_path = ApplyUrlMapping (worker_request.GetUriPath ());
1206 return original_path;
1210 public string Path {
1212 if (unescaped_path == null) {
1213 unescaped_path = PathNoValidation;
1215 if (validateRequestNewMode) {
1216 RequestValidator validator = RequestValidator.Current;
1217 int validationFailureIndex;
1219 if (!validator.IsValidRequestString (HttpContext.Current, unescaped_path, RequestValidationSource.Path, null, out validationFailureIndex))
1220 ThrowValidationException ("Path", "Path", unescaped_path);
1225 return unescaped_path;
1229 public string PathInfo {
1231 if (path_info == null) {
1232 if (worker_request == null)
1233 return String.Empty;
1234 path_info = worker_request.GetPathInfo () ?? String.Empty;
1236 if (validateRequestNewMode) {
1237 RequestValidator validator = RequestValidator.Current;
1238 int validationFailureIndex;
1240 if (!validator.IsValidRequestString (HttpContext.Current, path_info, RequestValidationSource.PathInfo, null, out validationFailureIndex))
1241 ThrowValidationException ("PathInfo", "PathInfo", path_info);
1250 public string PhysicalApplicationPath {
1252 if (worker_request == null)
1253 throw new ArgumentNullException (); // like 2.0, 1.x throws TypeInitializationException
1255 string path = HttpRuntime.AppDomainAppPath;
1256 if (SecurityManager.SecurityEnabled) {
1257 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
1263 public string PhysicalPath {
1265 if (worker_request == null)
1266 return String.Empty; // don't check security with an empty string!
1268 if (physical_path == null) {
1269 // Don't call HttpRequest.MapPath here, as that one *trims* the input
1270 physical_path = worker_request.MapPath (FilePath);
1273 if (SecurityManager.SecurityEnabled) {
1274 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, physical_path).Demand ();
1276 return physical_path;
1280 internal string RootVirtualDir {
1282 if (root_virtual_dir == null){
1283 string fp = FilePath;
1284 int p = fp.LastIndexOf ('/');
1287 root_virtual_dir = "/";
1289 root_virtual_dir = fp.Substring (0, p);
1291 return root_virtual_dir;
1295 internal WebROCollection QueryStringUnvalidated {
1297 if (query_string_nvc == null) {
1298 query_string_nvc = new WebROCollection ();
1299 string q = UrlComponents.Query;
1304 HttpUtility.ParseQueryString (q, ContentEncoding, query_string_nvc);
1307 query_string_nvc.Protect();
1310 return query_string_nvc;
1314 public NameValueCollection QueryString {
1316 NameValueCollection query_string_nvc = QueryStringUnvalidated;
1318 if (validateRequestNewMode && !checked_query_string) {
1319 if (!lazyQueryStringValidation) {
1320 // Setting this before calling the validator prevents
1321 // possible endless recursion
1322 checked_query_string = true;
1323 ValidateNameValueCollection ("QueryString", query_string_nvc, RequestValidationSource.QueryString);
1327 if (validate_query_string && !checked_query_string) {
1328 // Setting this before calling the validator prevents
1329 // possible endless recursion
1330 checked_query_string = true;
1331 ValidateNameValueCollection ("QueryString", query_string_nvc);
1334 return query_string_nvc;
1338 public string RawUrl {
1340 if (raw_url == null) {
1341 if (worker_request != null)
1342 raw_url = worker_request.GetRawUrl ();
1344 raw_url = UrlComponents.Path + UrlComponents.Query;
1346 if (raw_url == null)
1347 raw_url = String.Empty;
1349 if (validateRequestNewMode) {
1350 RequestValidator validator = RequestValidator.Current;
1351 int validationFailureIndex;
1353 if (!validator.IsValidRequestString (HttpContext.Current, raw_url, RequestValidationSource.RawUrl, null, out validationFailureIndex))
1354 ThrowValidationException ("RawUrl", "RawUrl", raw_url);
1366 public string RequestType {
1368 if (request_type == null){
1369 if (worker_request != null) {
1370 request_type = worker_request.GetHttpVerbName ();
1371 http_method = request_type;
1373 request_type = "GET";
1376 return request_type;
1380 request_type = value;
1384 public NameValueCollection ServerVariables {
1385 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
1387 if (server_variables == null)
1388 server_variables = new ServerVariablesCollection (this);
1390 return server_variables;
1394 public int TotalBytes {
1396 Stream ins = InputStream;
1397 return (int) ins.Length;
1403 if (cached_url == null) {
1404 if (orig_url == null)
1405 cached_url = UrlComponents.Uri;
1407 cached_url = new Uri (orig_url);
1414 public Uri UrlReferrer {
1416 if (worker_request == null)
1419 string hr = worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderReferer);
1426 } catch (UriFormatException) {}
1431 public string UserAgent {
1433 if (worker_request == null)
1436 return worker_request.GetKnownRequestHeader (HttpWorkerRequest.HeaderUserAgent);
1440 public string UserHostAddress {
1442 if (worker_request == null)
1445 return worker_request.GetRemoteAddress ();
1449 public string UserHostName {
1451 if (worker_request == null)
1454 return worker_request.GetRemoteName ();
1458 public string [] UserLanguages {
1460 if (worker_request == null)
1463 if (user_languages == null)
1464 user_languages = SplitHeader (HttpWorkerRequest.HeaderAcceptLanguage);
1466 return user_languages;
1470 public byte [] BinaryRead (int count)
1473 throw new ArgumentException ("count is < 0");
1475 Stream s = InputStream;
1476 byte [] ret = new byte [count];
1477 if (s.Read (ret, 0, count) != count)
1478 throw new ArgumentException (
1479 String.Format ("count {0} exceeds length of available input {1}",
1480 count, s.Length - s.Position));
1484 public int [] MapImageCoordinates (string imageFieldName)
1486 string method = HttpMethod;
1487 NameValueCollection coll = null;
1488 if (method == "HEAD" || method == "GET")
1490 else if (method == "POST")
1496 string x = coll [imageFieldName + ".x"];
1497 if (x == null || x == "")
1500 string y = coll [imageFieldName + ".y"];
1501 if (y == null || y == "")
1504 int [] result = new int [2];
1506 result [0] = Int32.Parse (x);
1507 result [1] = Int32.Parse (y);
1515 public string MapPath (string virtualPath)
1517 if (worker_request == null)
1520 return MapPath (virtualPath, BaseVirtualDir, true);
1523 public string MapPath (string virtualPath, string baseVirtualDir, bool allowCrossAppMapping)
1525 if (worker_request == null)
1526 throw HttpException.NewWithCode ("No HttpWorkerRequest", WebEventCodes.RuntimeErrorRequestAbort);
1528 if (virtualPath == null)
1531 virtualPath = virtualPath.Trim ();
1532 if (virtualPath.Length == 0)
1536 if (!VirtualPathUtility.IsValidVirtualPath (virtualPath))
1537 throw HttpException.NewWithCode (String.Format ("'{0}' is not a valid virtual path.", virtualPath), WebEventCodes.RuntimeErrorRequestAbort);
1539 string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
1540 if (!VirtualPathUtility.IsRooted (virtualPath)) {
1541 if (StrUtils.IsNullOrEmpty (baseVirtualDir))
1542 baseVirtualDir = appVirtualPath;
1543 virtualPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (baseVirtualDir), virtualPath);
1544 if (!VirtualPathUtility.IsAbsolute (virtualPath))
1545 virtualPath = VirtualPathUtility.ToAbsolute (virtualPath, false);
1546 } else if (!VirtualPathUtility.IsAbsolute (virtualPath))
1547 virtualPath = VirtualPathUtility.ToAbsolute (virtualPath, false);
1549 bool isAppVirtualPath = String.Compare (virtualPath, appVirtualPath, RuntimeHelpers.StringComparison) == 0;
1550 appVirtualPath = VirtualPathUtility.AppendTrailingSlash (appVirtualPath);
1551 if (!allowCrossAppMapping){
1552 if (!StrUtils.StartsWith (virtualPath, appVirtualPath, true))
1553 throw new ArgumentException ("MapPath: Mapping across applications not allowed");
1554 if (appVirtualPath.Length > 1 && virtualPath.Length > 1 && virtualPath [0] != '/')
1555 throw HttpException.NewWithCode ("MapPath: Mapping across applications not allowed", WebEventCodes.RuntimeErrorRequestAbort);
1558 if (!isAppVirtualPath && !virtualPath.StartsWith (appVirtualPath, RuntimeHelpers.StringComparison))
1559 throw new InvalidOperationException (String.Format ("Failed to map path '{0}'", virtualPath));
1560 string path = worker_request.MapPath (virtualPath);
1561 if (virtualPath [virtualPath.Length - 1] != '/' && path [path.Length - 1] == System.IO.Path.DirectorySeparatorChar)
1562 path = path.TrimEnd (System.IO.Path.DirectorySeparatorChar);
1566 public void SaveAs (string filename, bool includeHeaders)
1568 Stream output = new FileStream (filename, FileMode.Create);
1569 if (includeHeaders) {
1570 StringBuilder sb = new StringBuilder ();
1571 string version = String.Empty;
1573 if (worker_request != null) {
1574 version = worker_request.GetHttpVersion ();
1575 path = UrlComponents.Path;
1577 string qs = UrlComponents.Query;
1579 sb.AppendFormat ("{0} {1}{2} {3}\r\n", HttpMethod, path, qs, version);
1580 NameValueCollection coll = Headers;
1581 foreach (string k in coll.AllKeys) {
1584 sb.Append (coll [k]);
1589 byte [] bytes = Encoding.GetEncoding (28591).GetBytes (sb.ToString ());
1590 output.Write (bytes, 0, bytes.Length);
1593 // More than 1 call to SaveAs works fine on MS, so we "copy" the stream
1594 // to keep InputStream in its state.
1595 Stream input = GetSubStream (InputStream);
1597 long len = input.Length;
1598 int buf_size = (int) Math.Min ((len < 0 ? 0 : len), 8192);
1599 byte [] data = new byte [buf_size];
1601 while (len > 0 && (count = input.Read (data, 0, buf_size)) > 0) {
1602 output.Write (data, 0, count);
1608 EndSubStream (input);
1612 public void ValidateInput ()
1614 validate_cookies = true;
1615 validate_query_string = true;
1616 validate_form = true;
1618 inputValidationEnabled = true;
1622 internal void Validate ()
1624 var cfg = HttpRuntime.Section;
1625 string query = UrlComponents.Query;
1627 if (query != null && query.Length > cfg.MaxQueryStringLength)
1628 throw new HttpException (400, "The length of the query string for this request exceeds the configured maxQueryStringLength value.");
1630 string path = PathNoValidation;
1632 if (path.Length > cfg.MaxUrlLength)
1633 throw new HttpException (400, "The length of the URL for this request exceeds the configured maxUrlLength value.");
1635 char[] invalidChars = RequestPathInvalidCharacters;
1636 if (invalidChars != null) {
1637 int idx = path.IndexOfAny (invalidChars);
1639 throw HttpException.NewWithCode (
1640 String.Format ("A potentially dangerous Request.Path value was detected from the client ({0}).", path [idx]),
1641 WebEventCodes.RuntimeErrorValidationFailure
1646 if (validateRequestNewMode)
1650 #region internal routines
1651 internal string ClientTarget {
1653 return client_target;
1657 client_target = value;
1661 public bool IsLocal {
1663 string address = worker_request.GetRemoteAddress ();
1665 if (StrUtils.IsNullOrEmpty (address))
1668 if (address == "127.0.0.1")
1671 System.Net.IPAddress remoteAddr = System.Net.IPAddress.Parse (address);
1672 if (System.Net.IPAddress.IsLoopback (remoteAddr))
1675 for (int i = 0; i < host_addresses.Length; i++)
1676 if (remoteAddr.Equals (host_addresses [i]))
1683 internal void SetFilePath (string path)
1686 physical_path = null;
1687 original_path = null;
1690 internal void SetCurrentExePath (string path)
1693 current_exe_path = path;
1694 UrlComponents.Path = path + PathInfo;
1695 // recreated on demand
1696 root_virtual_dir = null;
1697 base_virtual_dir = null;
1698 physical_path = null;
1699 unescaped_path = null;
1700 original_path = null;
1703 internal void SetPathInfo (string pi)
1707 original_path = null;
1709 string path = UrlComponents.Path;
1710 UrlComponents.Path = path + PathInfo;
1713 internal void SetFormCollection (WebROCollection coll, bool lazyValidation)
1718 lazyFormValidation = lazyValidation;
1721 internal void SetQueryStringCollection (WebROCollection coll, bool lazyValidation)
1725 query_string_nvc = coll;
1726 lazyQueryStringValidation = lazyValidation;
1729 // Headers is ReadOnly, so we need this hack for cookie-less sessions.
1730 internal void SetHeader (string name, string value)
1732 WebROCollection h = (WebROCollection) Headers;
1738 // Notice: there is nothing raw about this querystring.
1739 internal string QueryStringRaw {
1741 UriBuilder urlComponents = UrlComponents;
1743 if (urlComponents == null) {
1744 string ret = worker_request.GetQueryString ();
1746 if (ret == null || ret.Length == 0)
1747 return String.Empty;
1755 return UrlComponents.Query;
1759 UrlComponents.Query = value;
1761 query_string_nvc = null;
1765 // Internal, dont know what it does, so flagged as public so we can see it.
1766 internal void SetForm (WebROCollection coll)
1771 internal HttpWorkerRequest WorkerRequest {
1773 return worker_request;
1777 internal HttpContext Context {
1778 get { return context; }
1779 set { context = value; }
1782 static void ValidateNameValueCollection (string name, NameValueCollection coll)
1787 foreach (string key in coll.Keys) {
1788 string val = coll [key];
1789 if (val != null && val.Length > 0 && IsInvalidString (val))
1790 ThrowValidationException (name, key, val);
1794 static void ValidateNameValueCollection (string name, NameValueCollection coll, RequestValidationSource source)
1799 RequestValidator validator = RequestValidator.Current;
1800 int validationFailureIndex;
1801 HttpContext context = HttpContext.Current;
1803 foreach (string key in coll.Keys) {
1804 string val = coll [key];
1805 if (val != null && val.Length > 0 && !validator.IsValidRequestString (context, val, source, key, out validationFailureIndex))
1806 ThrowValidationException (name, key, val);
1810 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
1811 public void InsertEntityBody ()
1813 throw new PlatformNotSupportedException ("This method is not supported.");
1816 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
1817 public void InsertEntityBody (byte[] buffer, int offset, int count)
1819 throw new PlatformNotSupportedException ("This method is not supported.");
1822 static void ValidateCookieCollection (HttpCookieCollection cookies)
1824 if (cookies == null)
1827 int size = cookies.Count;
1830 RequestValidator validator = RequestValidator.Current;
1831 int validationFailureIndex;
1832 HttpContext context = HttpContext.Current;
1836 for (int i = 0 ; i < size ; i++) {
1837 cookie = cookies[i];
1841 string value = cookie.Value;
1842 string name = cookie.Name;
1844 if (!String.IsNullOrEmpty (value)) {
1846 if (validateRequestNewMode)
1847 invalid = !validator.IsValidRequestString (context, value, RequestValidationSource.Cookies, name, out validationFailureIndex);
1850 invalid = IsInvalidString (value);
1853 ThrowValidationException ("Cookies", name, value);
1858 static void ThrowValidationException (string name, string key, string value)
1860 string v = "\"" + value + "\"";
1862 v = v.Substring (0, 16) + "...\"";
1864 string msg = String.Format ("A potentially dangerous Request.{0} value was " +
1865 "detected from the client ({1}={2}).", name, key, v);
1867 throw new HttpRequestValidationException (msg);
1870 internal static void ValidateString (string key, string value, RequestValidationSource source)
1872 if (String.IsNullOrEmpty (value))
1874 #pragma warning disable 219
1876 #pragma warning restore 219
1877 if (IsInvalidString (value, out ignore))
1878 ThrowValidationException (source.ToString (), key, value);
1881 internal static bool IsInvalidString (string val)
1883 #pragma warning disable 219
1884 int validationFailureIndex;
1885 #pragma warning restore 219
1886 return IsInvalidString (val, out validationFailureIndex);
1889 internal static bool IsInvalidString (string val, out int validationFailureIndex)
1891 validationFailureIndex = 0;
1893 int len = val.Length;
1897 char current = val [0];
1898 for (int idx = 1; idx < len; idx++) {
1899 char next = val [idx];
1900 // See http://secunia.com/advisories/14325
1901 if (current == '<' || current == '\xff1c') {
1902 if (next == '!' || next < ' '
1903 || (next >= 'a' && next <= 'z')
1904 || (next >= 'A' && next <= 'Z')) {
1905 validationFailureIndex = idx - 1;
1908 } else if (current == '&' && next == '#') {
1909 validationFailureIndex = idx - 1;
1919 static System.Net.IPAddress [] GetLocalHostAddresses ()
1922 string hostName = System.Net.Dns.GetHostName ();
1923 System.Net.IPAddress [] ipaddr = System.Net.Dns.GetHostAddresses (hostName);
1926 return new System.Net.IPAddress[0];
1932 #region Helper classes
1935 // Stream-based multipart handling.
1937 // In this incarnation deals with an HttpInputStream as we are now using
1938 // IntPtr-based streams instead of byte []. In the future, we will also
1939 // send uploads above a certain threshold into the disk (to implement
1940 // limit-less HttpInputFiles).
1943 class HttpMultipart {
1945 public class Element {
1946 public string ContentType;
1948 public string Filename;
1952 public override string ToString ()
1954 return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
1955 Start.ToString () + ", Length " + Length.ToString ();
1961 byte [] boundary_bytes;
1967 const byte HYPHEN = (byte) '-', LF = (byte) '\n', CR = (byte) '\r';
1970 // In the case of multipart entities, in which one or more different
1971 // sets of data are combined in a single body, a "multipart" media type
1972 // field must appear in the entity's header. The body must then contain
1973 // one or more body parts, each preceded by a boundary delimiter line,
1974 // and the last one followed by a closing boundary delimiter line.
1975 // After its boundary delimiter line, each body part then consists of a
1976 // header area, a blank line, and a body area. Thus a body part is
1977 // similar to an RFC 822 message in syntax, but different in meaning.
1979 public HttpMultipart (Stream data, string b, Encoding encoding)
1983 boundary_bytes = encoding.GetBytes (b);
1984 buffer = new byte [boundary_bytes.Length + 2]; // CRLF or '--'
1985 this.encoding = encoding;
1986 sb = new StringBuilder ();
1991 // CRLF or LF are ok as line endings.
1992 bool got_cr = false;
1996 b = data.ReadByte ();
2005 sb.Append ((char) b);
2011 return sb.ToString ();
2015 static string GetContentDispositionAttribute (string l, string name)
2017 int idx = l.IndexOf (name + "=\"");
2020 int begin = idx + name.Length + "=\"".Length;
2021 int end = l.IndexOf ('"', begin);
2026 return l.Substring (begin, end - begin);
2029 string GetContentDispositionAttributeWithEncoding (string l, string name)
2031 int idx = l.IndexOf (name + "=\"");
2034 int begin = idx + name.Length + "=\"".Length;
2035 int end = l.IndexOf ('"', begin);
2041 string temp = l.Substring (begin, end - begin);
2042 byte [] source = new byte [temp.Length];
2043 for (int i = temp.Length - 1; i >= 0; i--)
2044 source [i] = (byte) temp [i];
2046 return encoding.GetString (source);
2049 bool ReadBoundary ()
2052 string line = ReadLine ();
2055 if (line [0] != '-' || line [1] != '-')
2058 if (!StrUtils.EndsWith (line, boundary, false))
2066 string ReadHeaders ()
2068 string s = ReadLine ();
2075 bool CompareBytes (byte [] orig, byte [] other)
2077 for (int i = orig.Length - 1; i >= 0; i--)
2078 if (orig [i] != other [i])
2084 long MoveToNextBoundary ()
2087 bool got_cr = false;
2090 int c = data.ReadByte ();
2095 if (state == 0 && c == LF) {
2096 retval = data.Position - 1;
2100 c = data.ReadByte ();
2101 } else if (state == 0) {
2103 c = data.ReadByte ();
2104 } else if (state == 1 && c == '-') {
2105 c = data.ReadByte ();
2112 continue; // no ReadByte() here
2115 int nread = data.Read (buffer, 0, buffer.Length);
2116 int bl = buffer.Length;
2120 if (!CompareBytes (boundary_bytes, buffer)) {
2122 data.Position = retval + 2;
2127 c = data.ReadByte ();
2131 if (buffer [bl - 2] == '-' && buffer [bl - 1] == '-') {
2133 } else if (buffer [bl - 2] != CR || buffer [bl - 1] != LF) {
2135 data.Position = retval + 2;
2140 c = data.ReadByte ();
2143 data.Position = retval + 2;
2149 state = 0; // no ReadByte() here
2156 public Element ReadNextElement ()
2158 if (at_eof || ReadBoundary ())
2161 Element elem = new Element ();
2163 while ((header = ReadHeaders ()) != null) {
2164 if (StrUtils.StartsWith (header, "Content-Disposition:", true)) {
2165 elem.Name = GetContentDispositionAttribute (header, "name");
2166 elem.Filename = StripPath (GetContentDispositionAttributeWithEncoding (header, "filename"));
2167 } else if (StrUtils.StartsWith (header, "Content-Type:", true)) {
2168 elem.ContentType = header.Substring ("Content-Type:".Length).Trim ();
2172 long start = data.Position;
2174 long pos = MoveToNextBoundary ();
2178 elem.Length = pos - start;
2182 static string StripPath (string path)
2184 if (path == null || path.Length == 0)
2187 if (path.IndexOf (":\\") != 1 && !path.StartsWith ("\\\\"))
2189 return path.Substring (path.LastIndexOf ('\\') + 1);