3 // Copyright (c) Microsoft Corporation. All rights reserved.
8 // <OWNER>Microsoft</OWNER>
10 // Implementation of membership condition for zones
13 namespace System.Security.Util {
16 using System.Collections;
17 using System.Collections.Generic;
18 using System.Runtime.CompilerServices;
19 using System.Runtime.InteropServices;
20 using System.Runtime.Versioning;
21 using System.Runtime.Serialization;
22 using System.Globalization;
25 using System.Diagnostics.Contracts;
28 internal sealed class URLString : SiteString
30 private String m_protocol;
31 [OptionalField(VersionAdded = 2)]
32 private String m_userpass;
33 private SiteString m_siteString;
35 private LocalSiteString m_localSite;
36 private DirectoryString m_directory;
38 private const String m_defaultProtocol = "file";
40 [OptionalField(VersionAdded = 2)]
41 private bool m_parseDeferred;
42 [OptionalField(VersionAdded = 2)]
43 private String m_urlOriginal;
44 [OptionalField(VersionAdded = 2)]
45 private bool m_parsedOriginal;
47 [OptionalField(VersionAdded = 3)]
48 private bool m_isUncShare;
50 // legacy field from v1.x, not used in v2 and beyond. Retained purely for serialization compatability.
51 private String m_fullurl;
55 public void OnDeserialized(StreamingContext ctx)
58 if (m_urlOriginal == null)
60 // pre-v2 deserialization. Need to fix-up fields here
61 m_parseDeferred = false;
62 m_parsedOriginal = false; // Dont care what this value is - never used
64 m_urlOriginal = m_fullurl;
69 private void OnSerializing(StreamingContext ctx)
72 if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
75 m_fullurl = m_urlOriginal;
79 private void OnSerialized(StreamingContext ctx)
81 if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
91 m_siteString = new SiteString();
94 m_directory = new DirectoryString();
95 m_parseDeferred = false;
98 private void DoDeferredParse()
102 ParseString(m_urlOriginal, m_parsedOriginal);
103 m_parseDeferred = false;
107 public URLString(string url) : this(url, false, false) {}
108 public URLString(string url, bool parsed) : this(url, parsed, false) {}
110 internal URLString(string url, bool parsed, bool doDeferredParsing)
116 m_parsedOriginal = parsed;
117 m_parseDeferred = true;
118 if (doDeferredParsing)
122 // Converts %XX and %uYYYY to the actual characters (I.e. Unesacpes any escape characters present in the URL)
123 private String UnescapeURL(String url)
125 StringBuilder intermediate = StringBuilderCache.Acquire(url.Length);
126 int Rindex = 0; // index into temp that gives the rest of the string to be processed
130 braIndex = url.IndexOf('[',Rindex);
132 ketIndex = url.IndexOf(']', braIndex);
136 index = url.IndexOf( '%', Rindex);
140 intermediate = intermediate.Append(url, Rindex, (url.Length - Rindex));
143 // if we hit a '%' in the middle of an IPv6 address, dont process that
144 if (index > braIndex && index < ketIndex)
146 intermediate = intermediate.Append(url, Rindex, (ketIndex - Rindex+1));
151 if (url.Length - index < 2) // Check that there is at least 1 char after the '%'
152 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
154 if (url[index+1] == 'u' || url[index+1] == 'U')
156 if (url.Length - index < 6) // example: "%u004d" is 6 chars long
157 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
159 // We have a unicode character specified in hex
163 char c = (char)(Hex.ConvertHexDigit( url[index+2] ) << 12 |
164 Hex.ConvertHexDigit( url[index+3] ) << 8 |
165 Hex.ConvertHexDigit( url[index+4] ) << 4 |
166 Hex.ConvertHexDigit( url[index+5] ));
167 intermediate = intermediate.Append(url, Rindex, index - Rindex);
168 intermediate = intermediate.Append(c);
170 catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException
172 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
175 Rindex = index + 6 ; //update the 'seen' length
179 // we have a hex character.
181 if (url.Length - index < 3) // example: "%4d" is 3 chars long
182 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
186 char c = (char)(Hex.ConvertHexDigit( url[index+1] ) << 4 | Hex.ConvertHexDigit( url[index+2] ));
188 intermediate = intermediate.Append(url, Rindex, index - Rindex);
189 intermediate = intermediate.Append(c);
191 catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException
193 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
196 Rindex = index + 3; // update the 'seen' length
201 return StringBuilderCache.GetStringAndRelease(intermediate);
204 // Helper Function for ParseString:
205 // Search for the end of the protocol info and grab the actual protocol string
206 // ex. http://www.microsoft.com/complus would have a protocol string of http
207 private String ParseProtocol(String url)
210 int index = url.IndexOf( ':' );
214 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
216 else if (index == -1)
218 m_protocol = m_defaultProtocol;
221 else if (url.Length > index + 1)
223 if (index == m_defaultProtocol.Length &&
224 String.Compare(url, 0, m_defaultProtocol, 0, index, StringComparison.OrdinalIgnoreCase) == 0)
226 m_protocol = m_defaultProtocol;
227 temp = url.Substring( index + 1 );
229 // Since an explicit file:// URL could be immediately followed by a host name, we will be
230 // conservative and assume that it is on a share rather than a potentally relative local
234 else if (url[index+1] != '\\')
236 if (url.Length > index + 2 &&
237 url[index+1] == '/' &&
240 m_protocol = url.Substring( 0, index );
242 for (int i = 0; i < m_protocol.Length; ++i)
244 char c = m_protocol[i];
246 if ((c >= 'a' && c <= 'z') ||
247 (c >= 'A' && c <= 'Z') ||
248 (c >= '0' && c <= '9') ||
257 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
260 temp = url.Substring( index + 3 );
264 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
269 m_protocol = m_defaultProtocol;
275 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
281 private String ParsePort(String url)
284 char[] separators = new char[] { ':', '/' };
286 int userpassIndex = temp.IndexOf('@');
287 if (userpassIndex != -1) {
288 if (temp.IndexOf('/',0,userpassIndex) == -1) {
289 // this is a user:pass type of string
290 m_userpass = temp.Substring(0,userpassIndex);
291 Rindex = userpassIndex + 1;
298 braIndex = url.IndexOf('[',Rindex);
300 ketIndex = url.IndexOf(']', braIndex);
303 // IPv6 address...ignore the IPv6 block when searching for the port
304 portIndex = temp.IndexOfAny(separators,ketIndex);
308 portIndex = temp.IndexOfAny(separators,Rindex);
313 if (portIndex != -1 && temp[portIndex] == ':')
315 // make sure it really is a port, and has a number after the :
316 if ( temp[portIndex+1] >= '0' && temp[portIndex+1] <= '9' )
318 int tempIndex = temp.IndexOf( '/', Rindex);
322 m_port = Int32.Parse( temp.Substring(portIndex + 1), CultureInfo.InvariantCulture );
325 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
327 temp = temp.Substring( Rindex, portIndex - Rindex );
329 else if (tempIndex > portIndex)
331 m_port = Int32.Parse( temp.Substring(portIndex + 1, tempIndex - portIndex - 1), CultureInfo.InvariantCulture );
332 temp = temp.Substring( Rindex, portIndex - Rindex ) + temp.Substring( tempIndex );
335 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
338 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
341 // Chop of the user/pass portion if any
342 temp = temp.Substring(Rindex);
348 // This does three things:
349 // 1. It makes the following modifications to the start of the string:
350 // a. \\?\ and \\?/ => <empty>
351 // b. \\.\ and \\./ => <empty>
352 // 2. If isFileUrl is true, converts all slashes to front slashes and strips leading
353 // front slashes. See comment by code.
354 // 3. Throws a PathTooLongException if the length of the resulting URL is >= MAX_PATH.
355 // This is done to prevent security issues due to canonicalization truncations.
356 // Remove this method when the Path class supports "\\?\"
357 internal static String PreProcessForExtendedPathRemoval(String url, bool isFileUrl)
359 bool uncShare = false;
360 return PreProcessForExtendedPathRemoval(url, isFileUrl, ref uncShare);
363 private static String PreProcessForExtendedPathRemoval(String url, bool isFileUrl, ref bool isUncShare)
365 // This is the modified URL that we will return
366 StringBuilder modifiedUrl = new StringBuilder(url);
368 // ITEM 1 - remove extended path characters.
370 // Keep track of where we are in both the comparison and altered strings.
374 // If all the '\' have already been converted to '/', just check for //?/ or //./
375 if ((url.Length - curCmpIdx) >= 4 &&
376 (String.Compare(url, curCmpIdx, "//?/", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
377 String.Compare(url, curCmpIdx, "//./", 0, 4, StringComparison.OrdinalIgnoreCase) == 0))
379 modifiedUrl.Remove(curModIdx, 4);
385 // We need to handle an indefinite number of leading front slashes for file URLs since we could
386 // get something like:
391 while (url[curCmpIdx] == '/')
398 // Remove the extended path characters
399 if ((url.Length - curCmpIdx) >= 4 &&
400 (String.Compare(url, curCmpIdx, "\\\\?\\", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
401 String.Compare(url, curCmpIdx, "\\\\?/", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
402 String.Compare(url, curCmpIdx, "\\\\.\\", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
403 String.Compare(url, curCmpIdx, "\\\\./", 0, 4, StringComparison.OrdinalIgnoreCase) == 0))
405 modifiedUrl.Remove(curModIdx, 4);
411 // ITEM 2 - convert all slashes to forward slashes, and strip leading slashes.
415 bool seenFirstBackslash = false;
417 while (slashCount < modifiedUrl.Length && (modifiedUrl[slashCount] == '/' || modifiedUrl[slashCount] == '\\'))
419 // Look for sets of consecutive backslashes. We can't just look for these at the start
420 // of the string, since file:// might come first. Instead, once we see the first \, look
421 // for a second one following it.
422 if (!seenFirstBackslash && modifiedUrl[slashCount] == '\\')
424 seenFirstBackslash = true;
425 if (slashCount + 1 < modifiedUrl.Length && modifiedUrl[slashCount + 1] == '\\')
432 modifiedUrl.Remove(0, slashCount);
433 modifiedUrl.Replace('\\', '/');
436 // ITEM 3 - If the path is greater than or equal (due to terminating NULL in windows) MAX_PATH, we throw.
437 if (modifiedUrl.Length >= Path.MAX_PATH)
439 throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
442 // Create the result string from the StringBuilder
443 return modifiedUrl.ToString();
447 // Do any misc massaging of data in the URL
448 private String PreProcessURL(String url, bool isFileURL)
451 // Remove when the Path class supports "\\?\"
452 url = PreProcessForExtendedPathRemoval(url, true, ref m_isUncShare);
455 url = url.Replace('\\', '/');
460 private void ParseFileURL(String url)
464 int index = temp.IndexOf( '/');
468 temp[index-1] != ':' &&
469 temp[index-1] != '|') ||
471 index != temp.Length - 1)
473 // Also, if it is a UNC share, we want m_localSite to
474 // be of the form "computername/share", so if the first
475 // fileEnd character found is a slash, do some more parsing
476 // to find the proper end character.
478 int tempIndex = temp.IndexOf( '/', index+1);
490 localSite = temp.Substring(0,index);
492 if (localSite.Length == 0)
493 throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
498 if (localSite[0] == '\\' && localSite[1] == '\\')
500 spacesAllowed = true;
506 spacesAllowed = false;
509 bool useSmallCharToUpper = true;
511 for (; i < localSite.Length; ++i)
513 char c = localSite[i];
515 if ((c >= 'A' && c <= 'Z') ||
516 (c >= 'a' && c <= 'z') ||
517 (c >= '0' && c <= '9') ||
518 (c == '-') || (c == '/') ||
519 (c == ':') || (c == '|') ||
520 (c == '.') || (c == '*') ||
521 (c == '$') || (spacesAllowed && c == ' '))
527 useSmallCharToUpper = false;
532 if (useSmallCharToUpper)
533 localSite = String.SmallCharToUpper( localSite );
535 localSite = localSite.ToUpper(CultureInfo.InvariantCulture);
537 m_localSite = new LocalSiteString( localSite );
541 if (localSite[localSite.Length-1] == '*')
542 m_directory = new DirectoryString( "*", false );
544 m_directory = new DirectoryString();
548 String directoryString = temp.Substring( index + 1 );
549 if (directoryString.Length == 0)
551 m_directory = new DirectoryString();
555 m_directory = new DirectoryString( directoryString, true);
563 private void ParseNonFileURL(String url)
566 int index = temp.IndexOf('/');
570 m_localSite = null; // for drive letter
571 m_siteString = new SiteString( temp );
572 m_directory = new DirectoryString();
576 String site = temp.Substring( 0, index );
578 m_siteString = new SiteString( site );
580 String directoryString = temp.Substring( index + 1 );
582 if (directoryString.Length == 0)
584 m_directory = new DirectoryString();
588 m_directory = new DirectoryString( directoryString, false );
594 void DoFastChecks( String url )
598 throw new ArgumentNullException( "url" );
600 Contract.EndContractBlock();
604 throw new FormatException(Environment.GetResourceString("Format_StringZeroLength"));
609 // 1. We support URLs that follow the common Internet scheme syntax
610 // (<scheme>://user:pass@<host>:<port>/<url-path>) and all windows file URLs.
611 // 2. In the general case we parse of the site and create a SiteString out of it
612 // (which supports our wildcarding scheme). In the case of files we don't support
613 // wildcarding and furthermore SiteString doesn't like ':' and '|' which can appear
614 // in file urls so we just keep that info in a separate string and set the
615 // SiteString to null.
617 // ex. http://www.microsoft.com/complus -> m_siteString = "www.microsoft.com" m_localSite = null
618 // ex. file:///c:/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:"
619 // ex. file:///c|/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:"
620 void ParseString( String url, bool parsed )
622 // If there are any escaped hex or unicode characters in the url, translate those
623 // into the proper character.
627 url = UnescapeURL(url);
630 // Identify the protocol and strip the protocol info from the string, if present.
631 String temp = ParseProtocol(url);
633 bool fileProtocol = (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0);
635 // handle any special preocessing...removing extra characters, etc.
636 temp = PreProcessURL(temp, fileProtocol);
644 // Check if there is a port number and parse that out.
645 temp = ParsePort(temp);
646 ParseNonFileURL(temp);
647 // Note: that we allow DNS and Netbios names for non-file protocols (since sitestring will check
648 // that the hostname satisfies these two protocols. DNS-only checking can theoretically be added
649 // here but that would break all the programs that use '_' (which is fairly common, yet illegal).
650 // If this needs to be done at any point, add a call to m_siteString.IsLegalDNSName().
672 if (m_siteString != null)
674 return m_siteString.ToString();
678 return m_localSite.ToString();
692 return m_port.ToString(CultureInfo.InvariantCulture);
696 public String Directory
702 return m_directory.ToString();
707 /// Make a best guess at determining if this is URL refers to a file with a relative path. Since
708 /// this is a guess to help out users of UrlMembershipCondition who may accidentally supply a
709 /// relative URL, we'd rather err on the side of absolute than relative. (We'd rather accept some
710 /// meaningless membership conditions rather than reject meaningful ones).
712 /// In order to be a relative file URL, the URL needs to have a protocol of file, and not be on a
715 /// If both of the above are true, then the heuristics we'll use to detect an absolute URL are:
716 /// 1. A host name which is:
717 /// a. greater than one character and ends in a colon (representing the drive letter) OR
718 /// b. ends with a * (so we match any file with the given prefix if any)
719 /// 2. Has a directory name (cannot be simply file://c:)
721 public bool IsRelativeFileUrl
727 if (String.Equals(m_protocol, "file", StringComparison.OrdinalIgnoreCase) && !m_isUncShare)
729 string host = m_localSite != null ? m_localSite.ToString() : null;
730 // If the host name ends with the * character, treat this as an absolute URL since the *
731 // could represent the rest of the full path.
732 if (host.EndsWith('*'))
734 string directory = m_directory != null ? m_directory.ToString() : null;
736 return host == null || host.Length < 2 || !host.EndsWith(':') ||
737 String.IsNullOrEmpty(directory);
740 // Since this is not a local URL, it cannot be relative
745 public String GetFileName()
749 if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
752 String intermediateDirectory = this.Directory.Replace( '/', '\\' );
754 String directory = this.Host.Replace( '/', '\\' );
756 int directorySlashIndex = directory.IndexOf( '\\' );
757 if (directorySlashIndex == -1)
759 if (directory.Length != 2 ||
760 !(directory[1] == ':' || directory[1] == '|'))
762 directory = "\\\\" + directory;
765 else if (directorySlashIndex != 2 ||
766 (directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|'))
768 directory = "\\\\" + directory;
771 directory += "\\" + intermediateDirectory;
777 public String GetDirectoryName()
781 if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0)
784 String intermediateDirectory = this.Directory.Replace( '/', '\\' );
787 for (int i = intermediateDirectory.Length; i > 0; i--)
789 if (intermediateDirectory[i-1] == '\\')
796 String directory = this.Host.Replace( '/', '\\' );
798 int directorySlashIndex = directory.IndexOf( '\\' );
799 if (directorySlashIndex == -1)
801 if (directory.Length != 2 ||
802 !(directory[1] == ':' || directory[1] == '|'))
804 directory = "\\\\" + directory;
807 else if (directorySlashIndex > 2 ||
808 (directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|'))
810 directory = "\\\\" + directory;
817 directory += intermediateDirectory.Substring( 0, slashIndex );
823 public override SiteString Copy()
825 return new URLString( m_urlOriginal, m_parsedOriginal );
828 [ResourceExposure(ResourceScope.None)]
829 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
830 public override bool IsSubsetOf( SiteString site )
837 URLString url = site as URLString;
845 url.DoDeferredParse();
847 URLString normalUrl1 = this.SpecialNormalizeUrl();
848 URLString normalUrl2 = url.SpecialNormalizeUrl();
850 if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) == 0 &&
851 normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ))
853 if (normalUrl1.m_localSite != null)
855 // We do a little extra processing in here for local files since we allow
856 // both <drive_letter>: and <drive_letter>| forms of urls.
858 return normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite );
862 if (normalUrl1.m_port != normalUrl2.m_port)
865 return normalUrl2.m_siteString != null && normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString );
874 public override String ToString()
876 return m_urlOriginal;
879 public override bool Equals(Object o)
883 if (o == null || !(o is URLString))
886 return this.Equals( (URLString)o );
889 public override int GetHashCode()
893 TextInfo info = CultureInfo.InvariantCulture.TextInfo;
896 if (this.m_protocol != null)
897 accumulator = info.GetCaseInsensitiveHashCode( this.m_protocol );
899 if (this.m_localSite != null)
901 accumulator = accumulator ^ this.m_localSite.GetHashCode();
905 accumulator = accumulator ^ this.m_siteString.GetHashCode();
907 accumulator = accumulator ^ this.m_directory.GetHashCode();
912 public bool Equals( URLString url )
914 return CompareUrls( this, url );
917 [ResourceExposure(ResourceScope.None)]
918 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
919 public static bool CompareUrls( URLString url1, URLString url2 )
921 if (url1 == null && url2 == null)
924 if (url1 == null || url2 == null)
927 url1.DoDeferredParse();
928 url2.DoDeferredParse();
930 URLString normalUrl1 = url1.SpecialNormalizeUrl();
931 URLString normalUrl2 = url2.SpecialNormalizeUrl();
933 // Compare protocol (case insensitive)
935 if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) != 0)
938 // Do special processing for file urls
940 if (String.Compare( normalUrl1.m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0)
942 if (!normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite ) ||
943 !normalUrl2.m_localSite.IsSubsetOf( normalUrl1.m_localSite ))
948 if (String.Compare( normalUrl1.m_userpass, normalUrl2.m_userpass, StringComparison.Ordinal) != 0)
951 if (!normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString ) ||
952 !normalUrl2.m_siteString.IsSubsetOf( normalUrl1.m_siteString ))
955 if (url1.m_port != url2.m_port)
959 if (!normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ) ||
960 !normalUrl2.m_directory.IsSubsetOf( normalUrl1.m_directory ))
966 internal String NormalizeUrl()
969 StringBuilder builtUrl = StringBuilderCache.Acquire();
971 if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0)
973 builtUrl = builtUrl.AppendFormat("FILE:///{0}/{1}", m_localSite.ToString(), m_directory.ToString());
977 builtUrl = builtUrl.AppendFormat("{0}://{1}{2}", m_protocol, m_userpass, m_siteString.ToString());
980 builtUrl = builtUrl.AppendFormat("{0}",m_port);
982 builtUrl = builtUrl.AppendFormat("/{0}", m_directory.ToString());
985 return StringBuilderCache.GetStringAndRelease(builtUrl).ToUpper(CultureInfo.InvariantCulture);
988 [System.Security.SecuritySafeCritical] // auto-generated
989 [ResourceExposure(ResourceScope.Machine)]
990 [ResourceConsumption(ResourceScope.Machine)]
991 internal URLString SpecialNormalizeUrl()
993 // Under WinXP, file protocol urls can be mapped to
994 // drives that aren't actually file protocol underneath
995 // due to drive mounting. This code attempts to figure
996 // out what a drive is mounted to and create the
1000 if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
1006 String localSite = m_localSite.ToString();
1008 if (localSite.Length == 2 &&
1009 (localSite[1] == '|' ||
1010 localSite[1] == ':'))
1012 String deviceName = null;
1013 GetDeviceName(localSite, JitHelpers.GetStringHandleOnStack(ref deviceName));
1015 if (deviceName != null)
1017 if (deviceName.IndexOf( "://", StringComparison.Ordinal ) != -1)
1019 URLString u = new URLString( deviceName + "/" + this.m_directory.ToString() );
1020 u.DoDeferredParse(); // Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL
1025 URLString u = new URLString( "file://" + deviceName + "/" + this.m_directory.ToString() );
1026 u.DoDeferredParse();// Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL
1040 [System.Security.SecurityCritical] // auto-generated
1041 [ResourceExposure(ResourceScope.Machine)]
1042 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
1043 [SuppressUnmanagedCodeSecurity]
1044 private static extern void GetDeviceName( String driveLetter, StringHandleOnStack retDeviceName );
1049 internal class DirectoryString : SiteString
1051 private bool m_checkForIllegalChars;
1053 private new static char[] m_separators = { '/' };
1055 // From KB #Q177506, file/folder illegal characters are \ / : * ? " < > |
1056 protected static char[] m_illegalDirectoryCharacters = { '\\', ':', '*', '?', '"', '<', '>', '|' };
1058 public DirectoryString()
1061 m_separatedSite = new ArrayList();
1064 public DirectoryString( String directory, bool checkForIllegalChars )
1067 m_checkForIllegalChars = checkForIllegalChars;
1068 m_separatedSite = CreateSeparatedString(directory);
1071 private ArrayList CreateSeparatedString(String directory)
1073 if (directory == null || directory.Length == 0)
1075 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
1077 Contract.EndContractBlock();
1079 ArrayList list = new ArrayList();
1080 String[] separatedArray = directory.Split(m_separators);
1082 for (int index = 0; index < separatedArray.Length; ++index)
1084 if (separatedArray[index] == null || separatedArray[index].Equals( "" ))
1086 // this case is fine, we just ignore it the extra separators.
1088 else if (separatedArray[index].Equals( "*" ))
1090 if (index != separatedArray.Length-1)
1092 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
1094 list.Add( separatedArray[index] );
1096 else if (m_checkForIllegalChars && separatedArray[index].IndexOfAny( m_illegalDirectoryCharacters ) != -1)
1098 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
1102 list.Add( separatedArray[index] );
1109 public virtual bool IsSubsetOf( DirectoryString operand )
1111 return this.IsSubsetOf( operand, true );
1114 public virtual bool IsSubsetOf( DirectoryString operand, bool ignoreCase )
1116 if (operand == null)
1120 else if (operand.m_separatedSite.Count == 0)
1122 return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
1124 else if (this.m_separatedSite.Count == 0)
1126 return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
1130 return base.IsSubsetOf( operand, ignoreCase );
1136 internal class LocalSiteString : SiteString
1138 private new static char[] m_separators = { '/' };
1140 public LocalSiteString( String site )
1142 m_site = site.Replace( '|', ':');
1144 if (m_site.Length > 2 && m_site.IndexOf( ':' ) != -1)
1145 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
1147 m_separatedSite = CreateSeparatedString(m_site);
1150 private ArrayList CreateSeparatedString(String directory)
1152 if (directory == null || directory.Length == 0)
1154 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
1156 Contract.EndContractBlock();
1158 ArrayList list = new ArrayList();
1159 String[] separatedArray = directory.Split(m_separators);
1161 for (int index = 0; index < separatedArray.Length; ++index)
1163 if (separatedArray[index] == null || separatedArray[index].Equals( "" ))
1166 directory[index] == '/')
1170 else if (index != separatedArray.Length-1)
1172 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
1175 else if (separatedArray[index].Equals( "*" ))
1177 if (index != separatedArray.Length-1)
1179 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
1181 list.Add( separatedArray[index] );
1185 list.Add( separatedArray[index] );
1192 public virtual bool IsSubsetOf( LocalSiteString operand )
1194 return this.IsSubsetOf( operand, true );
1197 public virtual bool IsSubsetOf( LocalSiteString operand, bool ignoreCase )
1199 if (operand == null)
1203 else if (operand.m_separatedSite.Count == 0)
1205 return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
1207 else if (this.m_separatedSite.Count == 0)
1209 return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
1213 return base.IsSubsetOf( operand, ignoreCase );