diff options
Diffstat (limited to 'src/mscorlib/src/System/Security/Util')
-rw-r--r-- | src/mscorlib/src/System/Security/Util/Config.cs | 83 | ||||
-rw-r--r-- | src/mscorlib/src/System/Security/Util/Hex.cs | 126 | ||||
-rw-r--r-- | src/mscorlib/src/System/Security/Util/StringExpressionSet.cs | 752 | ||||
-rw-r--r-- | src/mscorlib/src/System/Security/Util/TokenBasedSet.cs | 443 | ||||
-rw-r--r-- | src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs | 36 | ||||
-rw-r--r-- | src/mscorlib/src/System/Security/Util/URLString.cs | 1237 | ||||
-rw-r--r-- | src/mscorlib/src/System/Security/Util/XMLUtil.cs | 435 | ||||
-rw-r--r-- | src/mscorlib/src/System/Security/Util/sitestring.cs | 289 |
8 files changed, 5 insertions, 3396 deletions
diff --git a/src/mscorlib/src/System/Security/Util/Config.cs b/src/mscorlib/src/System/Security/Util/Config.cs deleted file mode 100644 index afc9b8c336..0000000000 --- a/src/mscorlib/src/System/Security/Util/Config.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Security.Util { - using System; - using System.Security.Util; - using System.Security.Policy; - using System.Security.Permissions; - using System.Collections; - using System.IO; - using System.Reflection; - using System.Globalization; - using System.Text; -#if FEATURE_SERIALIZATION - using System.Runtime.Serialization.Formatters.Binary; -#endif // FEATURE_SERIALIZATION - using System.Threading; - using System.Runtime.CompilerServices; - using System.Runtime.InteropServices; - using System.Runtime.Versioning; - - // Duplicated in vm\COMSecurityConfig.h -[Serializable] -[Flags] - internal enum QuickCacheEntryType - { - FullTrustZoneMyComputer = 0x1000000, - FullTrustZoneIntranet = 0x2000000, - FullTrustZoneInternet = 0x4000000, - FullTrustZoneTrusted = 0x8000000, - FullTrustZoneUntrusted = 0x10000000, - FullTrustAll = 0x20000000, - } - - internal static class Config { - private static volatile string m_machineConfig; - private static volatile string m_userConfig; - - private static void GetFileLocales() - { - if (m_machineConfig == null) - { - string machineConfig = null; - GetMachineDirectory(JitHelpers.GetStringHandleOnStack(ref machineConfig)); - m_machineConfig = machineConfig; - } - if (m_userConfig == null) - { - string userConfig = null; - GetUserDirectory(JitHelpers.GetStringHandleOnStack(ref userConfig)); - m_userConfig = userConfig; - } - } - - internal static string MachineDirectory - { - get - { - GetFileLocales(); - return m_machineConfig; - } - } - - internal static string UserDirectory - { - get - { - GetFileLocales(); - return m_userConfig; - } - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - private static extern void GetMachineDirectory(StringHandleOnStack retDirectory); - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - private static extern void GetUserDirectory(StringHandleOnStack retDirectory); - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] - internal static extern bool WriteToEventLog(string message); - } -} diff --git a/src/mscorlib/src/System/Security/Util/Hex.cs b/src/mscorlib/src/System/Security/Util/Hex.cs deleted file mode 100644 index 4ca1cf678b..0000000000 --- a/src/mscorlib/src/System/Security/Util/Hex.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/* - * - * Operations to convert to and from Hex - * - */ - -namespace System.Security.Util -{ - using System; - using System.Security; - using System.Diagnostics.Contracts; - internal static class Hex - { - // converts number to hex digit. Does not do any range checks. - static char HexDigit(int num) { - return (char)((num < 10) ? (num + '0') : (num + ('A' - 10))); - } - - public static String EncodeHexString(byte[] sArray) - { - String result = null; - - if(sArray != null) { - char[] hexOrder = new char[sArray.Length * 2]; - - int digit; - for(int i = 0, j = 0; i < sArray.Length; i++) { - digit = (int)((sArray[i] & 0xf0) >> 4); - hexOrder[j++] = HexDigit(digit); - digit = (int)(sArray[i] & 0x0f); - hexOrder[j++] = HexDigit(digit); - } - result = new String(hexOrder); - } - return result; - } - - internal static string EncodeHexStringFromInt(byte[] sArray) { - String result = null; - if(sArray != null) { - char[] hexOrder = new char[sArray.Length * 2]; - - int i = sArray.Length; - int digit, j=0; - while (i-- > 0) { - digit = (sArray[i] & 0xf0) >> 4; - hexOrder[j++] = HexDigit(digit); - digit = sArray[i] & 0x0f; - hexOrder[j++] = HexDigit(digit); - } - result = new String(hexOrder); - } - return result; - } - - public static int ConvertHexDigit(Char val) - { - if (val <= '9' && val >= '0') - return (val - '0'); - else if (val >= 'a' && val <= 'f') - return ((val - 'a') + 10); - else if (val >= 'A' && val <= 'F') - return ((val - 'A') + 10); - else - throw new ArgumentException( Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); - } - - - public static byte[] DecodeHexString(String hexString) - { - if (hexString == null) - throw new ArgumentNullException( nameof(hexString) ); - Contract.EndContractBlock(); - - bool spaceSkippingMode = false; - - int i = 0; - int length = hexString.Length; - - if ((length >= 2) && - (hexString[0] == '0') && - ( (hexString[1] == 'x') || (hexString[1] == 'X') )) - { - length = hexString.Length - 2; - i = 2; - } - - // Hex strings must always have 2N or (3N - 1) entries. - - if (length % 2 != 0 && length % 3 != 2) - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidHexFormat" ) ); - } - - byte[] sArray; - - if (length >=3 && hexString[i + 2] == ' ') - { - spaceSkippingMode = true; - - // Each hex digit will take three spaces, except the first (hence the plus 1). - sArray = new byte[length / 3 + 1]; - } - else - { - // Each hex digit will take two spaces - sArray = new byte[length / 2]; - } - - int digit; - int rawdigit; - for (int j = 0; i < hexString.Length; i += 2, j++) { - rawdigit = ConvertHexDigit(hexString[i]); - digit = ConvertHexDigit(hexString[i+1]); - sArray[j] = (byte) (digit | (rawdigit << 4)); - if (spaceSkippingMode) - i++; - } - return(sArray); - } - } -} diff --git a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs b/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs deleted file mode 100644 index 8a12235106..0000000000 --- a/src/mscorlib/src/System/Security/Util/StringExpressionSet.cs +++ /dev/null @@ -1,752 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Security.Util { - using System.Text; - using System; - using System.Collections; - using System.Collections.Generic; - using System.Runtime.CompilerServices; - using System.Runtime.InteropServices; - using System.Globalization; - using System.Runtime.Versioning; - using System.IO; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - [Serializable] - internal class StringExpressionSet - { - // This field, as well as the expressions fields below are critical since they may contain - // canonicalized full path data potentially built out of relative data passed as input to the - // StringExpressionSet. Full trust code using the string expression set needs to ensure that before - // exposing this data out to partial trust, they protect against this. Possibilities include: - // - // 1. Using the throwOnRelative flag - // 2. Ensuring that the partial trust code has permission to see full path data - // 3. Not using this set for paths (eg EnvironmentStringExpressionSet) - // - protected ArrayList m_list; - protected bool m_ignoreCase; - protected String m_expressions; - protected String[] m_expressionsArray; - - protected bool m_throwOnRelative; - - protected static readonly char[] m_separators = { ';' }; - protected static readonly char[] m_trimChars = { ' ' }; -#if !PLATFORM_UNIX - protected static readonly char m_directorySeparator = '\\'; - protected static readonly char m_alternateDirectorySeparator = '/'; -#else - protected static readonly char m_directorySeparator = '/'; - protected static readonly char m_alternateDirectorySeparator = '\\'; -#endif // !PLATFORM_UNIX - - public StringExpressionSet() - : this( true, null, false ) - { - } - - public StringExpressionSet( String str ) - : this( true, str, false ) - { - } - - public StringExpressionSet( bool ignoreCase, bool throwOnRelative ) - : this( ignoreCase, null, throwOnRelative ) - { - } - - public StringExpressionSet( bool ignoreCase, String str, bool throwOnRelative ) - { - m_list = null; - m_ignoreCase = ignoreCase; - m_throwOnRelative = throwOnRelative; - if (str == null) - m_expressions = null; - else - AddExpressions( str ); - } - - protected virtual StringExpressionSet CreateNewEmpty() - { - return new StringExpressionSet(); - } - - public virtual StringExpressionSet Copy() - { - // SafeCritical: just copying this value around, not leaking it - - StringExpressionSet copy = CreateNewEmpty(); - if (this.m_list != null) - copy.m_list = new ArrayList(this.m_list); - - copy.m_expressions = this.m_expressions; - copy.m_ignoreCase = this.m_ignoreCase; - copy.m_throwOnRelative = this.m_throwOnRelative; - return copy; - } - - public void SetThrowOnRelative( bool throwOnRelative ) - { - this.m_throwOnRelative = throwOnRelative; - } - - private static String StaticProcessWholeString( String str ) - { - return str.Replace( m_alternateDirectorySeparator, m_directorySeparator ); - } - - private static String StaticProcessSingleString( String str ) - { - return str.Trim( m_trimChars ); - } - - protected virtual String ProcessWholeString( String str ) - { - return StaticProcessWholeString(str); - } - - protected virtual String ProcessSingleString( String str ) - { - return StaticProcessSingleString(str); - } - - public void AddExpressions( String str ) - { - if (str == null) - throw new ArgumentNullException( nameof(str) ); - Contract.EndContractBlock(); - if (str.Length == 0) - return; - - str = ProcessWholeString( str ); - - if (m_expressions == null) - m_expressions = str; - else - m_expressions = m_expressions + m_separators[0] + str; - - m_expressionsArray = null; - - // We have to parse the string and compute the list here. - // The logic in this class tries to delay this parsing but - // since operations like IsSubsetOf are called during - // demand evaluation, it is not safe to delay this step - // as that would cause concurring threads to update the object - // at the same time. The CheckList operation should ideally be - // removed from this class, but for the sake of keeping the - // changes to a minimum here, we simply make sure m_list - // cannot be null by parsing m_expressions eagerly. - - String[] arystr = Split( str ); - - if (m_list == null) - m_list = new ArrayList(); - - for (int index = 0; index < arystr.Length; ++index) - { - if (arystr[index] != null && !arystr[index].Equals( "" )) - { - String temp = ProcessSingleString( arystr[index] ); - int indexOfNull = temp.IndexOf( '\0' ); - - if (indexOfNull != -1) - temp = temp.Substring( 0, indexOfNull ); - - if (temp != null && !temp.Equals( "" )) - { - if (m_throwOnRelative) - { - if (PathInternal.IsPartiallyQualified(temp)) - { - throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); - } - - temp = CanonicalizePath( temp ); - } - - m_list.Add( temp ); - } - } - } - - Reduce(); - } - - public void AddExpressions( String[] str, bool checkForDuplicates, bool needFullPath ) - { - AddExpressions(CreateListFromExpressions(str, needFullPath), checkForDuplicates); - } - - public void AddExpressions( ArrayList exprArrayList, bool checkForDuplicates) - { - Debug.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" ); - - m_expressionsArray = null; - m_expressions = null; - - if (m_list != null) - m_list.AddRange(exprArrayList); - else - m_list = new ArrayList(exprArrayList); - - if (checkForDuplicates) - Reduce(); - } - - - internal static ArrayList CreateListFromExpressions(String[] str, bool needFullPath) - { - if (str == null) - { - throw new ArgumentNullException( nameof(str) ); - } - Contract.EndContractBlock(); - ArrayList retArrayList = new ArrayList(); - for (int index = 0; index < str.Length; ++index) - { - if (str[index] == null) - throw new ArgumentNullException( nameof(str) ); - - // Replace alternate directory separators - String oneString = StaticProcessWholeString( str[index] ); - - if (oneString != null && oneString.Length != 0) - { - // Trim leading and trailing spaces - String temp = StaticProcessSingleString( oneString); - - int indexOfNull = temp.IndexOf( '\0' ); - - if (indexOfNull != -1) - temp = temp.Substring( 0, indexOfNull ); - - if (temp != null && temp.Length != 0) - { - if (PathInternal.IsPartiallyQualified(temp)) - { - throw new ArgumentException(Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); - } - - temp = CanonicalizePath( temp, needFullPath ); - - retArrayList.Add( temp ); - } - } - } - - return retArrayList; - } - - protected void CheckList() - { - if (m_list == null && m_expressions != null) - { - CreateList(); - } - } - - protected String[] Split( String expressions ) - { - if (m_throwOnRelative) - { - List<String> tempList = new List<String>(); - - String[] quoteSplit = expressions.Split( '\"' ); - - for (int i = 0; i < quoteSplit.Length; ++i) - { - if (i % 2 == 0) - { - String[] semiSplit = quoteSplit[i].Split( ';' ); - - for (int j = 0; j < semiSplit.Length; ++j) - { - if (semiSplit[j] != null && !semiSplit[j].Equals( "" )) - tempList.Add( semiSplit[j] ); - } - } - else - { - tempList.Add( quoteSplit[i] ); - } - } - - String[] finalArray = new String[tempList.Count]; - - IEnumerator enumerator = tempList.GetEnumerator(); - - int index = 0; - while (enumerator.MoveNext()) - { - finalArray[index++] = (String)enumerator.Current; - } - - return finalArray; - } - else - { - return expressions.Split( m_separators ); - } - } - - - protected void CreateList() - { - String[] expressionsArray = Split( m_expressions ); - - m_list = new ArrayList(); - - for (int index = 0; index < expressionsArray.Length; ++index) - { - if (expressionsArray[index] != null && !expressionsArray[index].Equals( "" )) - { - String temp = ProcessSingleString( expressionsArray[index] ); - - int indexOfNull = temp.IndexOf( '\0' ); - - if (indexOfNull != -1) - temp = temp.Substring( 0, indexOfNull ); - - if (temp != null && !temp.Equals( "" )) - { - if (m_throwOnRelative) - { - if (PathInternal.IsPartiallyQualified(temp)) - { - throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); - } - - temp = CanonicalizePath( temp ); - } - - m_list.Add( temp ); - } - } - } - } - - public bool IsEmpty() - { - // SafeCritical: we're just showing that the expressions are empty, the sensitive portion is their - // contents - not the existence of the contents - if (m_list == null) - { - return m_expressions == null; - } - else - { - return m_list.Count == 0; - } - } - - public bool IsSubsetOf( StringExpressionSet ses ) - { - if (this.IsEmpty()) - return true; - - if (ses == null || ses.IsEmpty()) - return false; - - CheckList(); - ses.CheckList(); - - for (int index = 0; index < this.m_list.Count; ++index) - { - if (!StringSubsetStringExpression( (String)this.m_list[index], ses, m_ignoreCase )) - { - return false; - } - } - return true; - } - - public bool IsSubsetOfPathDiscovery( StringExpressionSet ses ) - { - if (this.IsEmpty()) - return true; - - if (ses == null || ses.IsEmpty()) - return false; - - CheckList(); - ses.CheckList(); - - for (int index = 0; index < this.m_list.Count; ++index) - { - if (!StringSubsetStringExpressionPathDiscovery( (String)this.m_list[index], ses, m_ignoreCase )) - { - return false; - } - } - return true; - } - - - public StringExpressionSet Union( StringExpressionSet ses ) - { - // If either set is empty, the union represents a copy of the other. - - if (ses == null || ses.IsEmpty()) - return this.Copy(); - - if (this.IsEmpty()) - return ses.Copy(); - - CheckList(); - ses.CheckList(); - - // Perform the union - // note: insert smaller set into bigger set to reduce needed comparisons - - StringExpressionSet bigger = ses.m_list.Count > this.m_list.Count ? ses : this; - StringExpressionSet smaller = ses.m_list.Count <= this.m_list.Count ? ses : this; - - StringExpressionSet unionSet = bigger.Copy(); - - unionSet.Reduce(); - - for (int index = 0; index < smaller.m_list.Count; ++index) - { - unionSet.AddSingleExpressionNoDuplicates( (String)smaller.m_list[index] ); - } - - unionSet.GenerateString(); - - return unionSet; - } - - - public StringExpressionSet Intersect( StringExpressionSet ses ) - { - // If either set is empty, the intersection is empty - - if (this.IsEmpty() || ses == null || ses.IsEmpty()) - return CreateNewEmpty(); - - CheckList(); - ses.CheckList(); - - // Do the intersection for real - - StringExpressionSet intersectSet = CreateNewEmpty(); - - for (int this_index = 0; this_index < this.m_list.Count; ++this_index) - { - for (int ses_index = 0; ses_index < ses.m_list.Count; ++ses_index) - { - if (StringSubsetString( (String)this.m_list[this_index], (String)ses.m_list[ses_index], m_ignoreCase )) - { - if (intersectSet.m_list == null) - { - intersectSet.m_list = new ArrayList(); - } - intersectSet.AddSingleExpressionNoDuplicates( (String)this.m_list[this_index] ); - } - else if (StringSubsetString( (String)ses.m_list[ses_index], (String)this.m_list[this_index], m_ignoreCase )) - { - if (intersectSet.m_list == null) - { - intersectSet.m_list = new ArrayList(); - } - intersectSet.AddSingleExpressionNoDuplicates( (String)ses.m_list[ses_index] ); - } - } - } - - intersectSet.GenerateString(); - - return intersectSet; - } - - protected void GenerateString() - { - // SafeCritical - moves critical data around, but doesn't expose it out - if (m_list != null) - { - StringBuilder sb = new StringBuilder(); - - IEnumerator enumerator = this.m_list.GetEnumerator(); - bool first = true; - - while (enumerator.MoveNext()) - { - if (!first) - sb.Append( m_separators[0] ); - else - first = false; - - String currentString = (String)enumerator.Current; - if (currentString != null) - { - int indexOfSeparator = currentString.IndexOf( m_separators[0] ); - - if (indexOfSeparator != -1) - sb.Append( '\"' ); - - sb.Append( currentString ); - - if (indexOfSeparator != -1) - sb.Append( '\"' ); - } - } - - m_expressions = sb.ToString(); - } - else - { - m_expressions = null; - } - } - - // We don't override ToString since that API must be either transparent or safe citical. If the - // expressions contain paths that were canonicalized and expanded from the input that would cause - // information disclosure, so we instead only expose this out to trusted code that can ensure they - // either don't leak the information or required full path information. - public string UnsafeToString() - { - CheckList(); - - Reduce(); - - GenerateString(); - - return m_expressions; - } - - public String[] UnsafeToStringArray() - { - if (m_expressionsArray == null && m_list != null) - { - m_expressionsArray = (String[])m_list.ToArray(typeof(String)); - } - - return m_expressionsArray; - } - - - //------------------------------- - // protected static helper functions - //------------------------------- - - private bool StringSubsetStringExpression( String left, StringExpressionSet right, bool ignoreCase ) - { - for (int index = 0; index < right.m_list.Count; ++index) - { - if (StringSubsetString( left, (String)right.m_list[index], ignoreCase )) - { - return true; - } - } - return false; - } - - private static bool StringSubsetStringExpressionPathDiscovery( String left, StringExpressionSet right, bool ignoreCase ) - { - for (int index = 0; index < right.m_list.Count; ++index) - { - if (StringSubsetStringPathDiscovery( left, (String)right.m_list[index], ignoreCase )) - { - return true; - } - } - return false; - } - - - protected virtual bool StringSubsetString( String left, String right, bool ignoreCase ) - { - StringComparison strComp = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); - if (right == null || left == null || right.Length == 0 || left.Length == 0 || - right.Length > left.Length) - { - return false; - } - else if (right.Length == left.Length) - { - // if they are equal in length, just do a normal compare - return String.Compare( right, left, strComp) == 0; - } - else if (left.Length - right.Length == 1 && left[left.Length-1] == m_directorySeparator) - { - return String.Compare( left, 0, right, 0, right.Length, strComp) == 0; - } - else if (right[right.Length-1] == m_directorySeparator) - { - // right is definitely a directory, just do a substring compare - return String.Compare( right, 0, left, 0, right.Length, strComp) == 0; - } - else if (left[right.Length] == m_directorySeparator) - { - // left is hinting at being a subdirectory on right, do substring compare to make find out - return String.Compare( right, 0, left, 0, right.Length, strComp) == 0; - } - else - { - return false; - } - } - - protected static bool StringSubsetStringPathDiscovery( String left, String right, bool ignoreCase ) - { - StringComparison strComp = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); - if (right == null || left == null || right.Length == 0 || left.Length == 0) - { - return false; - } - else if (right.Length == left.Length) - { - // if they are equal in length, just do a normal compare - return String.Compare( right, left, strComp) == 0; - } - else - { - String shortString, longString; - - if (right.Length < left.Length) - { - shortString = right; - longString = left; - } - else - { - shortString = left; - longString = right; - } - - if (String.Compare( shortString, 0, longString, 0, shortString.Length, strComp) != 0) - { - return false; - } - -#if !PLATFORM_UNIX - if (shortString.Length == 3 && - shortString.EndsWith( ":\\", StringComparison.Ordinal ) && - ((shortString[0] >= 'A' && shortString[0] <= 'Z') || - (shortString[0] >= 'a' && shortString[0] <= 'z'))) -#else - if (shortString.Length == 1 && shortString[0]== m_directorySeparator) -#endif // !PLATFORM_UNIX - return true; - - return longString[shortString.Length] == m_directorySeparator; - } - } - - - //------------------------------- - // protected helper functions - //------------------------------- - - protected void AddSingleExpressionNoDuplicates( String expression ) - { - // SafeCritical: We're not exposing out the string sets, just allowing modification of them - int index = 0; - - m_expressionsArray = null; - m_expressions = null; - - if (this.m_list == null) - this.m_list = new ArrayList(); - - while (index < this.m_list.Count) - { - if (StringSubsetString( (String)this.m_list[index], expression, m_ignoreCase )) - { - this.m_list.RemoveAt( index ); - } - else if (StringSubsetString( expression, (String)this.m_list[index], m_ignoreCase )) - { - return; - } - else - { - index++; - } - } - this.m_list.Add( expression ); - } - - protected void Reduce() - { - CheckList(); - - if (this.m_list == null) - return; - - int j; - - for (int i = 0; i < this.m_list.Count - 1; i++) - { - j = i + 1; - - while (j < this.m_list.Count) - { - if (StringSubsetString( (String)this.m_list[j], (String)this.m_list[i], m_ignoreCase )) - { - this.m_list.RemoveAt( j ); - } - else if (StringSubsetString( (String)this.m_list[i], (String)this.m_list[j], m_ignoreCase )) - { - // write the value at j into position i, delete the value at position j and keep going. - this.m_list[i] = this.m_list[j]; - this.m_list.RemoveAt( j ); - j = i + 1; - } - else - { - j++; - } - } - } - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - internal static extern void GetLongPathName( String path, StringHandleOnStack retLongPath ); - - internal static String CanonicalizePath( String path ) - { - return CanonicalizePath( path, true ); - } - - internal static string CanonicalizePath(string path, bool needFullPath) - { - if (needFullPath) - { - string newPath = Path.GetFullPath(path); - if (path.EndsWith(m_directorySeparator + ".", StringComparison.Ordinal)) - { - if (newPath.EndsWith(m_directorySeparator)) - { - newPath += "."; - } - else - { - newPath += m_directorySeparator + "."; - } - } - path = newPath; - } -#if !PLATFORM_UNIX - else if (path.IndexOf('~') != -1) - { - // GetFullPathInternal() will expand 8.3 file names - string longPath = null; - GetLongPathName(path, JitHelpers.GetStringHandleOnStack(ref longPath)); - path = (longPath != null) ? longPath : path; - } - - // This blocks usage of alternate data streams and some extended syntax paths (\\?\C:\). Checking after - // normalization allows valid paths such as " C:\" to be considered ok (as it will become "C:\"). - if (path.IndexOf(':', 2) != -1) - throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported")); -#endif // !PLATFORM_UNIX - - return path; - } - } -} diff --git a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs b/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs deleted file mode 100644 index 8589fa7c42..0000000000 --- a/src/mscorlib/src/System/Security/Util/TokenBasedSet.cs +++ /dev/null @@ -1,443 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Security.Util -{ - using System; - using System.Collections; - using System.Security.Permissions; - using System.Runtime.Serialization; - using System.Threading; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Diagnostics.CodeAnalysis; - -#if FEATURE_SERIALIZATION - [Serializable] -#endif - internal class TokenBasedSet - { - - - // Following 3 fields are used only for serialization compat purposes: DO NOT USE THESE EVER! -#pragma warning disable 414 - private int m_initSize = 24; - private int m_increment = 8; -#pragma warning restore 414 - private Object[] m_objSet; - // END -> Serialization only fields - - [OptionalField(VersionAdded = 2)] - private volatile Object m_Obj; - [OptionalField(VersionAdded = 2)] - private volatile Object[] m_Set; - - private int m_cElt; - private volatile int m_maxIndex; - - - [OnDeserialized] - private void OnDeserialized(StreamingContext ctx) - { - OnDeserializedInternal(); - } - private void OnDeserializedInternal() - { - if (m_objSet != null) //v1.x case - { - if (m_cElt == 1) - m_Obj = m_objSet[m_maxIndex]; - else - m_Set = m_objSet; - m_objSet = null; - } - // Nothing to do for the v2.0 and beyond case - } - - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - //Nothing special for the v2 and beyond case - - // for the v1.x case, we need to create m_objSet if necessary - if (m_cElt == 1) - { - m_objSet = new Object[m_maxIndex+1]; - m_objSet[m_maxIndex] = m_Obj; - } - else if (m_cElt > 0) - { - // Array case: - m_objSet = m_Set; - } - - } - } - [OnSerialized] - private void OnSerialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_objSet = null; - - } - } - - - internal bool MoveNext(ref TokenBasedSetEnumerator e) - { - switch (m_cElt) - { - case 0: - return false; - - case 1: - if (e.Index == -1) - { - e.Index = m_maxIndex; - e.Current = m_Obj; - return true; - } - else - { - e.Index = (short)(m_maxIndex+1); - e.Current = null; - return false; - } - - default: - while (++e.Index <= m_maxIndex) - { - e.Current = Volatile.Read(ref m_Set[e.Index]); - - if (e.Current != null) - return true; - } - - e.Current = null; - return false; - } - } - - internal TokenBasedSet() - { - Reset(); - } - - [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")] - internal TokenBasedSet(TokenBasedSet tbSet) - { - if (tbSet == null) - { - Reset(); - return; - } - - if (tbSet.m_cElt > 1) - { - Object[] aObj = tbSet.m_Set; - int aLen = aObj.Length; - - Object[] aNew = new Object[aLen]; - System.Array.Copy(aObj, 0, aNew, 0, aLen); - - m_Set = aNew; - } - else - { - m_Obj = tbSet.m_Obj; - } - - m_cElt = tbSet.m_cElt; - m_maxIndex = tbSet.m_maxIndex; - } - - internal void Reset() - { - m_Obj = null; - m_Set = null; - m_cElt = 0; - m_maxIndex = -1; - } - - internal void SetItem(int index, Object item) - { - Object[] aObj = null; - - if (item == null) - { - RemoveItem(index); - return; - } - - switch (m_cElt) - { - case 0: - // on the first item, we don't create an array, we merely remember it's index and value - // this this the 99% case - m_cElt = 1; - m_maxIndex = (short)index; - m_Obj = item; - break; - - case 1: - // we have to decide if a 2nd item has indeed been added and create the array - // if it has - if (index == m_maxIndex) - { - // replacing the one existing item - m_Obj = item; - } - else - { - // adding a second distinct permission - Object objSaved = m_Obj; - int iMax = Math.Max(m_maxIndex, index); - - aObj = new Object[iMax+1]; - aObj[m_maxIndex] = objSaved; - aObj[index] = item; - m_maxIndex = (short)iMax; - m_cElt = 2; - m_Set = aObj; - m_Obj = null; - } - break; - - default: - // this is the general case code for when there is really an array - - aObj = m_Set; - - // we are now adding an item, check if we need to grow - - if (index >= aObj.Length) - { - Object[] newset = new Object[index+1]; - System.Array.Copy(aObj, 0, newset, 0, m_maxIndex+1); - m_maxIndex = (short)index; - newset[index] = item; - m_Set = newset; - m_cElt++; - } - else - { - if (aObj[index] == null) - m_cElt++; - - aObj[index] = item; - - if (index > m_maxIndex) - m_maxIndex = (short)index; - } - break; - } - } - - [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")] - internal Object GetItem(int index) - { - switch (m_cElt) - { - case 0: - return null; - - case 1: - if (index == m_maxIndex) - return m_Obj; - else - return null; - default: - if (index < m_Set.Length) - return Volatile.Read(ref m_Set[index]); - else - return null; - } - } - - internal Object RemoveItem(int index) - { - Object ret = null; - - switch (m_cElt) - { - case 0: - ret = null; - break; - - case 1: - if (index != m_maxIndex) - { - // removing a permission we don't have ignore it - ret = null; - } - else - { - // removing the permission we have at the moment - ret = m_Obj; - Reset(); - } - break; - - default: - // this is the general case code for when there is really an array - - // we are removing an item - if (index < m_Set.Length && (ret = Volatile.Read(ref m_Set[index])) != null) - { - // ok we really deleted something at this point - - Volatile.Write(ref m_Set[index], null); - m_cElt--; - - if (index == m_maxIndex) - ResetMaxIndex(m_Set); - - // collapse the array - if (m_cElt == 1) - { - m_Obj = Volatile.Read(ref m_Set[m_maxIndex]); - m_Set = null; - } - } - break; - } - - return ret; - } - - private void ResetMaxIndex(Object[] aObj) - { - int i; - - // Start at the end of the array, and - // scan backwards for the first non-null - // slot. That is the new maxIndex. - for (i = aObj.Length - 1; i >= 0; i--) - { - if (aObj[i] != null) - { - m_maxIndex = (short)i; - return; - } - } - - m_maxIndex = -1; - } - internal int GetStartingIndex() - { - if (m_cElt <= 1) - return m_maxIndex; - return 0; - } - internal int GetCount() - { - return m_cElt; - } - - internal int GetMaxUsedIndex() - { - return m_maxIndex; - } - - internal bool FastIsEmpty() - { - return m_cElt == 0; - } - - // Used to merge two distinct TokenBasedSets (used currently only in PermissionSet Deserialization) - internal TokenBasedSet SpecialUnion(TokenBasedSet other) - { - // This gets called from PermissionSet.OnDeserialized and it's possible that the TokenBasedSets have - // not been subjected to VTS callbacks yet - OnDeserializedInternal(); - TokenBasedSet unionSet = new TokenBasedSet(); - int maxMax; - if (other != null) - { - other.OnDeserializedInternal(); - maxMax = this.GetMaxUsedIndex() > other.GetMaxUsedIndex() ? this.GetMaxUsedIndex() : other.GetMaxUsedIndex(); - } - else - maxMax = this.GetMaxUsedIndex(); - - for (int i = 0; i <= maxMax; ++i) - { - Object thisObj = this.GetItem( i ); - IPermission thisPerm = thisObj as IPermission; - - Object otherObj = (other != null)?other.GetItem( i ):null; - IPermission otherPerm = otherObj as IPermission; - - if (thisObj == null && otherObj == null) - continue; - - if (thisObj == null) - { - PermissionToken token = PermissionToken.GetToken(otherPerm); - - if (token == null) - { - throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); - } - - unionSet.SetItem(token.m_index, otherPerm); - } - else if (otherObj == null) - { - PermissionToken token = PermissionToken.GetToken(thisPerm); - if (token == null) - { - throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); - } - unionSet.SetItem( token.m_index, thisPerm); - } - else - { - Debug.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" ); - } - } - return unionSet; - } - - internal void SpecialSplit(ref TokenBasedSet unrestrictedPermSet, ref TokenBasedSet normalPermSet, bool ignoreTypeLoadFailures) - { - int maxIndex = GetMaxUsedIndex(); - - for (int i = GetStartingIndex(); i <= maxIndex; ++i) - { - Object obj = GetItem( i ); - if (obj != null) - { - IPermission perm = obj as IPermission; - PermissionToken token = PermissionToken.GetToken(perm); - - if (perm == null || token == null) - continue; - - if (perm is IUnrestrictedPermission) - { - // Add to unrestrictedPermSet - if (unrestrictedPermSet == null) - unrestrictedPermSet = new TokenBasedSet(); - unrestrictedPermSet.SetItem(token.m_index, perm); - } - else - { - // Add to normalPermSet - if (normalPermSet == null) - normalPermSet = new TokenBasedSet(); - normalPermSet.SetItem(token.m_index, perm); - } - - } - - } - - } - } -} diff --git a/src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs b/src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs deleted file mode 100644 index 9c868d3c53..0000000000 --- a/src/mscorlib/src/System/Security/Util/TokenBasedSetEnumerator.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Security.Util -{ - using System; - using System.Collections; - - internal struct TokenBasedSetEnumerator - { - public Object Current; - public int Index; - - private TokenBasedSet _tb; - - public bool MoveNext() - { - return _tb != null ? _tb.MoveNext(ref this) : false; - } - - public void Reset() - { - Index = -1; - Current = null; - } - - public TokenBasedSetEnumerator(TokenBasedSet tb) - { - Index = -1; - Current = null; - _tb = tb; - } - } -} - diff --git a/src/mscorlib/src/System/Security/Util/URLString.cs b/src/mscorlib/src/System/Security/Util/URLString.cs index 83f9ce483f..4ec353876a 100644 --- a/src/mscorlib/src/System/Security/Util/URLString.cs +++ b/src/mscorlib/src/System/Security/Util/URLString.cs @@ -22,368 +22,8 @@ namespace System.Security.Util { using System.IO; using System.Diagnostics.Contracts; -#if FEATURE_SERIALIZATION - [Serializable] -#endif - internal sealed class URLString : SiteString + internal static class URLString { - private String m_protocol; - [OptionalField(VersionAdded = 2)] - private String m_userpass; - private SiteString m_siteString; - private int m_port; -#if !PLATFORM_UNIX - private LocalSiteString m_localSite; -#endif // !PLATFORM_UNIX - private DirectoryString m_directory; - - private const String m_defaultProtocol = "file"; - - [OptionalField(VersionAdded = 2)] - private bool m_parseDeferred; - [OptionalField(VersionAdded = 2)] - private String m_urlOriginal; - [OptionalField(VersionAdded = 2)] - private bool m_parsedOriginal; - - [OptionalField(VersionAdded = 3)] - private bool m_isUncShare; - - // legacy field from v1.x, not used in v2 and beyond. Retained purely for serialization compatibility. - private String m_fullurl; - - - [OnDeserialized] - public void OnDeserialized(StreamingContext ctx) - { - - if (m_urlOriginal == null) - { - // pre-v2 deserialization. Need to fix-up fields here - m_parseDeferred = false; - m_parsedOriginal = false; // Dont care what this value is - never used - m_userpass = ""; - m_urlOriginal = m_fullurl; - m_fullurl = null; - } - } - [OnSerializing] - private void OnSerializing(StreamingContext ctx) - { - - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - DoDeferredParse(); - m_fullurl = m_urlOriginal; - } - } - [OnSerialized] - private void OnSerialized(StreamingContext ctx) - { - if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) - { - m_fullurl = null; - } - } - - public URLString() - { - m_protocol = ""; - m_userpass = ""; - m_siteString = new SiteString(); - m_port = -1; -#if !PLATFORM_UNIX - m_localSite = null; -#endif // !PLATFORM_UNIX - m_directory = new DirectoryString(); - m_parseDeferred = false; - } - - private void DoDeferredParse() - { - if (m_parseDeferred) - { - ParseString(m_urlOriginal, m_parsedOriginal); - m_parseDeferred = false; - } - } - - public URLString(string url) : this(url, false, false) {} - public URLString(string url, bool parsed) : this(url, parsed, false) {} - - internal URLString(string url, bool parsed, bool doDeferredParsing) - { - m_port = -1; - m_userpass = ""; - DoFastChecks(url); - m_urlOriginal = url; - m_parsedOriginal = parsed; - m_parseDeferred = true; - if (doDeferredParsing) - DoDeferredParse(); - } - - // Converts %XX and %uYYYY to the actual characters (I.e. Unesacpes any escape characters present in the URL) - private String UnescapeURL(String url) - { - StringBuilder intermediate = StringBuilderCache.Acquire(url.Length); - int Rindex = 0; // index into temp that gives the rest of the string to be processed - int index; - int braIndex = -1; - int ketIndex = -1; - braIndex = url.IndexOf('[',Rindex); - if (braIndex != -1) - ketIndex = url.IndexOf(']', braIndex); - - do - { - index = url.IndexOf( '%', Rindex); - - if (index == -1) - { - intermediate = intermediate.Append(url, Rindex, (url.Length - Rindex)); - break; - } - // if we hit a '%' in the middle of an IPv6 address, dont process that - if (index > braIndex && index < ketIndex) - { - intermediate = intermediate.Append(url, Rindex, (ketIndex - Rindex+1)); - Rindex = ketIndex+1; - continue; - } - - if (url.Length - index < 2) // Check that there is at least 1 char after the '%' - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - - if (url[index+1] == 'u' || url[index+1] == 'U') - { - if (url.Length - index < 6) // example: "%u004d" is 6 chars long - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - - // We have a unicode character specified in hex - - try - { - char c = (char)(Hex.ConvertHexDigit( url[index+2] ) << 12 | - Hex.ConvertHexDigit( url[index+3] ) << 8 | - Hex.ConvertHexDigit( url[index+4] ) << 4 | - Hex.ConvertHexDigit( url[index+5] )); - intermediate = intermediate.Append(url, Rindex, index - Rindex); - intermediate = intermediate.Append(c); - } - catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - - Rindex = index + 6 ; //update the 'seen' length - } - else - { - // we have a hex character. - - if (url.Length - index < 3) // example: "%4d" is 3 chars long - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - - try - { - char c = (char)(Hex.ConvertHexDigit( url[index+1] ) << 4 | Hex.ConvertHexDigit( url[index+2] )); - - intermediate = intermediate.Append(url, Rindex, index - Rindex); - intermediate = intermediate.Append(c); - } - catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - - Rindex = index + 3; // update the 'seen' length - } - - } - while (true); - return StringBuilderCache.GetStringAndRelease(intermediate); - } - - // Helper Function for ParseString: - // Search for the end of the protocol info and grab the actual protocol string - // ex. http://www.microsoft.com/complus would have a protocol string of http - private String ParseProtocol(String url) - { - String temp; - int index = url.IndexOf( ':' ); - - if (index == 0) - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - else if (index == -1) - { - m_protocol = m_defaultProtocol; - temp = url; - } - else if (url.Length > index + 1) - { - if (index == m_defaultProtocol.Length && - String.Compare(url, 0, m_defaultProtocol, 0, index, StringComparison.OrdinalIgnoreCase) == 0) - { - m_protocol = m_defaultProtocol; - temp = url.Substring( index + 1 ); - - // Since an explicit file:// URL could be immediately followed by a host name, we will be - // conservative and assume that it is on a share rather than a potentally relative local - // URL. - m_isUncShare = true; - } - else if (url[index+1] != '\\') - { -#if !PLATFORM_UNIX - if (url.Length > index + 2 && - url[index+1] == '/' && - url[index+2] == '/') -#else - if (url.Length > index + 1 && - url[index+1] == '/' ) // UNIX style "file:/home/me" is allowed, so account for that -#endif // !PLATFORM_UNIX - { - m_protocol = url.Substring( 0, index ); - - for (int i = 0; i < m_protocol.Length; ++i) - { - char c = m_protocol[i]; - - if ((c >= 'a' && c <= 'z') || - (c >= 'A' && c <= 'Z') || - (c >= '0' && c <= '9') || - (c == '+') || - (c == '.') || - (c == '-')) - { - continue; - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - } -#if !PLATFORM_UNIX - temp = url.Substring( index + 3 ); -#else - // In UNIX, we don't know how many characters we'll have to skip past. - // Skip past \, /, and : - // - for ( int j=index ; j<url.Length ; j++ ) - { - if ( url[j] != '\\' && url[j] != '/' && url[j] != ':' ) - { - index = j; - break; - } - } - - temp = url.Substring( index ); -#endif // !PLATFORM_UNIX - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - } - else - { - m_protocol = m_defaultProtocol; - temp = url; - } - } - else - { - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - - return temp; - } - - private String ParsePort(String url) - { - String temp = url; - char[] separators = new char[] { ':', '/' }; - int Rindex = 0; - int userpassIndex = temp.IndexOf('@'); - if (userpassIndex != -1) { - if (temp.IndexOf('/',0,userpassIndex) == -1) { - // this is a user:pass type of string - m_userpass = temp.Substring(0,userpassIndex); - Rindex = userpassIndex + 1; - } - } - - int braIndex = -1; - int ketIndex = -1; - int portIndex = -1; - braIndex = url.IndexOf('[',Rindex); - if (braIndex != -1) - ketIndex = url.IndexOf(']', braIndex); - if (ketIndex != -1) - { - // IPv6 address...ignore the IPv6 block when searching for the port - portIndex = temp.IndexOfAny(separators,ketIndex); - } - else - { - portIndex = temp.IndexOfAny(separators,Rindex); - } - - - - if (portIndex != -1 && temp[portIndex] == ':') - { - // make sure it really is a port, and has a number after the : - if ( temp[portIndex+1] >= '0' && temp[portIndex+1] <= '9' ) - { - int tempIndex = temp.IndexOf( '/', Rindex); - - if (tempIndex == -1) - { - m_port = Int32.Parse( temp.Substring(portIndex + 1), CultureInfo.InvariantCulture ); - - if (m_port < 0) - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - - temp = temp.Substring( Rindex, portIndex - Rindex ); - } - else if (tempIndex > portIndex) - { - m_port = Int32.Parse( temp.Substring(portIndex + 1, tempIndex - portIndex - 1), CultureInfo.InvariantCulture ); - temp = temp.Substring( Rindex, portIndex - Rindex ) + temp.Substring( tempIndex ); - } - else - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - else - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - } - else { - // Chop of the user/pass portion if any - temp = temp.Substring(Rindex); - } - - return temp; - } - - // This does three things: - // 1. It makes the following modifications to the start of the string: - // a. \\?\ and \\?/ => <empty> - // b. \\.\ and \\./ => <empty> - // 2. If isFileUrl is true, converts all slashes to front slashes and strips leading - // front slashes. See comment by code. - // 3. Throws a PathTooLongException if the length of the resulting URL is >= MAX_PATH. - // This is done to prevent security issues due to canonicalization truncations. - // Remove this method when the Path class supports "\\?\" - internal static string PreProcessForExtendedPathRemoval(string url, bool isFileUrl) - { - return PreProcessForExtendedPathRemoval(checkPathLength: true, url: url, isFileUrl: isFileUrl); - } - internal static string PreProcessForExtendedPathRemoval(bool checkPathLength, string url, bool isFileUrl) { bool isUncShare = false; @@ -417,7 +57,8 @@ namespace System.Security.Util { } else { - if (isFileUrl) { + if (isFileUrl) + { // We need to handle an indefinite number of leading front slashes for file URLs since we could // get something like: // file://\\?\ @@ -449,14 +90,14 @@ namespace System.Security.Util { { int slashCount = 0; bool seenFirstBackslash = false; - + while (slashCount < modifiedUrl.Length && (modifiedUrl[slashCount] == '/' || modifiedUrl[slashCount] == '\\')) { // Look for sets of consecutive backslashes. We can't just look for these at the start // of the string, since file:// might come first. Instead, once we see the first \, look // for a second one following it. if (!seenFirstBackslash && modifiedUrl[slashCount] == '\\') - { + { seenFirstBackslash = true; if (slashCount + 1 < modifiedUrl.Length && modifiedUrl[slashCount + 1] == '\\') isUncShare = true; @@ -493,873 +134,5 @@ namespace System.Security.Util { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } } - - // Do any misc massaging of data in the URL - private String PreProcessURL(String url, bool isFileURL) - { - -#if !PLATFORM_UNIX - if (isFileURL) { - // Remove when the Path class supports "\\?\" - url = PreProcessForExtendedPathRemoval(url, true, ref m_isUncShare); - } - else { - url = url.Replace('\\', '/'); - } - return url; -#else - // Remove superfluous '/' - // For UNIX, the file path would look something like: - // file:///home/johndoe/here - // file:/home/johndoe/here - // file:../johndoe/here - // file:~/johndoe/here - String temp = url; - int nbSlashes = 0; - while(nbSlashes<temp.Length && '/'==temp[nbSlashes]) - nbSlashes++; - - // if we get a path like file:///directory/name we need to convert - // this to /directory/name. - if(nbSlashes > 2) - temp = temp.Substring(nbSlashes-1, temp.Length - (nbSlashes-1)); - else if (2 == nbSlashes) /* it's a relative path */ - temp = temp.Substring(nbSlashes, temp.Length - nbSlashes); - return temp; -#endif // !PLATFORM_UNIX - - } - - private void ParseFileURL(String url) - { - - String temp = url; -#if !PLATFORM_UNIX - int index = temp.IndexOf( '/'); - - if (index != -1 && - ((index == 2 && - temp[index-1] != ':' && - temp[index-1] != '|') || - index != 2) && - index != temp.Length - 1) - { - // Also, if it is a UNC share, we want m_localSite to - // be of the form "computername/share", so if the first - // fileEnd character found is a slash, do some more parsing - // to find the proper end character. - - int tempIndex = temp.IndexOf( '/', index+1); - - if (tempIndex != -1) - index = tempIndex; - else - index = -1; - } - - String localSite; - if (index == -1) - localSite = temp; - else - localSite = temp.Substring(0,index); - - if (localSite.Length == 0) - throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) ); - - int i; - bool spacesAllowed; - - if (localSite[0] == '\\' && localSite[1] == '\\') - { - spacesAllowed = true; - i = 2; - } - else - { - i = 0; - spacesAllowed = false; - } - - bool useSmallCharToUpper = true; - - for (; i < localSite.Length; ++i) - { - char c = localSite[i]; - - if ((c >= 'A' && c <= 'Z') || - (c >= 'a' && c <= 'z') || - (c >= '0' && c <= '9') || - (c == '-') || (c == '/') || - (c == ':') || (c == '|') || - (c == '.') || (c == '*') || - (c == '$') || (spacesAllowed && c == ' ')) - { - continue; - } - else - { - useSmallCharToUpper = false; - break; - } - } - - if (useSmallCharToUpper) - localSite = String.SmallCharToUpper( localSite ); - else - localSite = localSite.ToUpper(CultureInfo.InvariantCulture); - - m_localSite = new LocalSiteString( localSite ); - - if (index == -1) - { - if (localSite[localSite.Length-1] == '*') - m_directory = new DirectoryString( "*", false ); - else - m_directory = new DirectoryString(); - } - else - { - String directoryString = temp.Substring( index + 1 ); - if (directoryString.Length == 0) - { - m_directory = new DirectoryString(); - } - else - { - m_directory = new DirectoryString( directoryString, true); - } - } -#else // !PLATFORM_UNIX - m_directory = new DirectoryString( temp, true); -#endif // !PLATFORM_UNIX - - m_siteString = null; - return; - } - - private void ParseNonFileURL(String url) - { - String temp = url; - int index = temp.IndexOf('/'); - - if (index == -1) - { -#if !PLATFORM_UNIX - m_localSite = null; // for drive letter -#endif // !PLATFORM_UNIX - m_siteString = new SiteString( temp ); - m_directory = new DirectoryString(); - } - else - { -#if !PLATFORM_UNIX - String site = temp.Substring( 0, index ); - m_localSite = null; - m_siteString = new SiteString( site ); - - String directoryString = temp.Substring( index + 1 ); - - if (directoryString.Length == 0) - { - m_directory = new DirectoryString(); - } - else - { - m_directory = new DirectoryString( directoryString, false ); - } -#else - String directoryString = temp.Substring( index + 1 ); - String site = temp.Substring( 0, index ); - m_directory = new DirectoryString( directoryString, false ); - m_siteString = new SiteString( site ); -#endif //!PLATFORM_UNIX - } - return; - } - - void DoFastChecks( String url ) - { - if (url == null) - { - throw new ArgumentNullException( nameof(url) ); - } - Contract.EndContractBlock(); - - if (url.Length == 0) - { - throw new FormatException(Environment.GetResourceString("Format_StringZeroLength")); - } - } - - // NOTE: - // 1. We support URLs that follow the common Internet scheme syntax - // (<scheme>://user:pass@<host>:<port>/<url-path>) and all windows file URLs. - // 2. In the general case we parse of the site and create a SiteString out of it - // (which supports our wildcarding scheme). In the case of files we don't support - // wildcarding and furthermore SiteString doesn't like ':' and '|' which can appear - // in file urls so we just keep that info in a separate string and set the - // SiteString to null. - // - // ex. http://www.microsoft.com/complus -> m_siteString = "www.microsoft.com" m_localSite = null - // ex. file:///c:/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:" - // ex. file:///c|/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:" - void ParseString( String url, bool parsed ) - { - // If there are any escaped hex or unicode characters in the url, translate those - // into the proper character. - - if (!parsed) - { - url = UnescapeURL(url); - } - - // Identify the protocol and strip the protocol info from the string, if present. - String temp = ParseProtocol(url); - - bool fileProtocol = (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0); - - // handle any special preocessing...removing extra characters, etc. - temp = PreProcessURL(temp, fileProtocol); - - if (fileProtocol) - { - ParseFileURL(temp); - } - else - { - // Check if there is a port number and parse that out. - temp = ParsePort(temp); - ParseNonFileURL(temp); - // Note: that we allow DNS and Netbios names for non-file protocols (since sitestring will check - // that the hostname satisfies these two protocols. DNS-only checking can theoretically be added - // here but that would break all the programs that use '_' (which is fairly common, yet illegal). - // If this needs to be done at any point, add a call to m_siteString.IsLegalDNSName(). - } - - - } - - public String Scheme - { - get - { - DoDeferredParse(); - - return m_protocol; - } - } - - public String Host - { - get - { - DoDeferredParse(); - - if (m_siteString != null) - { - return m_siteString.ToString(); - } - else - { -#if !PLATFORM_UNIX - return m_localSite.ToString(); -#else - return ""; -#endif // !PLATFORM_UNIX - } - } - } - - public String Port - { - get - { - DoDeferredParse(); - - if (m_port == -1) - return null; - else - return m_port.ToString(CultureInfo.InvariantCulture); - } - } - - public String Directory - { - get - { - DoDeferredParse(); - - return m_directory.ToString(); - } - } - - /// <summary> - /// Make a best guess at determining if this is URL refers to a file with a relative path. Since - /// this is a guess to help out users of UrlMembershipCondition who may accidentally supply a - /// relative URL, we'd rather err on the side of absolute than relative. (We'd rather accept some - /// meaningless membership conditions rather than reject meaningful ones). - /// - /// In order to be a relative file URL, the URL needs to have a protocol of file, and not be on a - /// UNC share. - /// - /// If both of the above are true, then the heuristics we'll use to detect an absolute URL are: - /// 1. A host name which is: - /// a. greater than one character and ends in a colon (representing the drive letter) OR - /// b. ends with a * (so we match any file with the given prefix if any) - /// 2. Has a directory name (cannot be simply file://c:) - /// </summary> - public bool IsRelativeFileUrl - { - get - { - DoDeferredParse(); - - if (String.Equals(m_protocol, "file", StringComparison.OrdinalIgnoreCase) && !m_isUncShare) - { -#if !PLATFORM_UNIX - string host = m_localSite != null ? m_localSite.ToString() : null; - // If the host name ends with the * character, treat this as an absolute URL since the * - // could represent the rest of the full path. - if (host.EndsWith('*')) - return false; -#endif // !PLATFORM_UNIX - string directory = m_directory != null ? m_directory.ToString() : null; - -#if !PLATFORM_UNIX - return host == null || host.Length < 2 || !host.EndsWith(':') || - String.IsNullOrEmpty(directory); -#else - return String.IsNullOrEmpty(directory); -#endif // !PLATFORM_UNIX - - } - - // Since this is not a local URL, it cannot be relative - return false; - } - } - - public String GetFileName() - { - DoDeferredParse(); - -#if !PLATFORM_UNIX - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0) - return null; - - String intermediateDirectory = this.Directory.Replace( '/', '\\' ); - - String directory = this.Host.Replace( '/', '\\' ); - - int directorySlashIndex = directory.IndexOf( '\\' ); - if (directorySlashIndex == -1) - { - if (directory.Length != 2 || - !(directory[1] == ':' || directory[1] == '|')) - { - directory = "\\\\" + directory; - } - } - else if (directorySlashIndex != 2 || - (directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|')) - { - directory = "\\\\" + directory; - } - - directory += "\\" + intermediateDirectory; - - return directory; -#else - // In Unix, directory contains the full pathname - // (this is what we get in Win32) - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0) - return null; - - return this.Directory; -#endif // !PLATFORM_UNIX - } - - - public String GetDirectoryName() - { - DoDeferredParse(); - -#if !PLATFORM_UNIX - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0) - return null; - - String intermediateDirectory = this.Directory.Replace( '/', '\\' ); - - int slashIndex = 0; - for (int i = intermediateDirectory.Length; i > 0; i--) - { - if (intermediateDirectory[i-1] == '\\') - { - slashIndex = i; - break; - } - } - - String directory = this.Host.Replace( '/', '\\' ); - - int directorySlashIndex = directory.IndexOf( '\\' ); - if (directorySlashIndex == -1) - { - if (directory.Length != 2 || - !(directory[1] == ':' || directory[1] == '|')) - { - directory = "\\\\" + directory; - } - } - else if (directorySlashIndex > 2 || - (directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|')) - { - directory = "\\\\" + directory; - } - - directory += "\\"; - - if (slashIndex > 0) - { - directory += intermediateDirectory.Substring( 0, slashIndex ); - } - - return directory; -#else - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0) - return null; - - String directory = this.Directory.ToString(); - int slashIndex = 0; - for (int i = directory.Length; i > 0; i--) - { - if (directory[i-1] == '/') - { - slashIndex = i; - break; - } - } - - if (slashIndex > 0) - { - directory = directory.Substring( 0, slashIndex ); - } - - return directory; -#endif // !PLATFORM_UNIX - } - - public override SiteString Copy() - { - return new URLString( m_urlOriginal, m_parsedOriginal ); - } - - public override bool IsSubsetOf( SiteString site ) - { - if (site == null) - { - return false; - } - - URLString url = site as URLString; - - if (url == null) - { - return false; - } - - DoDeferredParse(); - url.DoDeferredParse(); - - URLString normalUrl1 = this.SpecialNormalizeUrl(); - URLString normalUrl2 = url.SpecialNormalizeUrl(); - - if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) == 0 && - normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory )) - { -#if !PLATFORM_UNIX - if (normalUrl1.m_localSite != null) - { - // We do a little extra processing in here for local files since we allow - // both <drive_letter>: and <drive_letter>| forms of urls. - - return normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite ); - } - else -#endif // !PLATFORM_UNIX - { - if (normalUrl1.m_port != normalUrl2.m_port) - return false; - - return normalUrl2.m_siteString != null && normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString ); - } - } - else - { - return false; - } - } - - public override String ToString() - { - return m_urlOriginal; - } - - public override bool Equals(Object o) - { - DoDeferredParse(); - - if (o == null || !(o is URLString)) - return false; - else - return this.Equals( (URLString)o ); - } - - public override int GetHashCode() - { - DoDeferredParse(); - - TextInfo info = CultureInfo.InvariantCulture.TextInfo; - int accumulator = 0; - - if (this.m_protocol != null) - accumulator = info.GetCaseInsensitiveHashCode( this.m_protocol ); - -#if !PLATFORM_UNIX - if (this.m_localSite != null) - { - accumulator = accumulator ^ this.m_localSite.GetHashCode(); - } - else - { - accumulator = accumulator ^ this.m_siteString.GetHashCode(); - } - accumulator = accumulator ^ this.m_directory.GetHashCode(); -#else - accumulator = accumulator ^ info.GetCaseInsensitiveHashCode(this.m_urlOriginal); -#endif // !PLATFORM_UNIX - - - - return accumulator; - } - - public bool Equals( URLString url ) - { - return CompareUrls( this, url ); - } - - public static bool CompareUrls( URLString url1, URLString url2 ) - { - if (url1 == null && url2 == null) - return true; - - if (url1 == null || url2 == null) - return false; - - url1.DoDeferredParse(); - url2.DoDeferredParse(); - - URLString normalUrl1 = url1.SpecialNormalizeUrl(); - URLString normalUrl2 = url2.SpecialNormalizeUrl(); - - // Compare protocol (case insensitive) - - if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) != 0) - return false; - - // Do special processing for file urls - - if (String.Compare( normalUrl1.m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0) - { -#if !PLATFORM_UNIX - if (!normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite ) || - !normalUrl2.m_localSite.IsSubsetOf( normalUrl1.m_localSite )) - return false; -#else - return url1.IsSubsetOf( url2 ) && - url2.IsSubsetOf( url1 ); -#endif // !PLATFORM_UNIX - } - else - { - if (String.Compare( normalUrl1.m_userpass, normalUrl2.m_userpass, StringComparison.Ordinal) != 0) - return false; - - if (!normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString ) || - !normalUrl2.m_siteString.IsSubsetOf( normalUrl1.m_siteString )) - return false; - - if (url1.m_port != url2.m_port) - return false; - } - - if (!normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ) || - !normalUrl2.m_directory.IsSubsetOf( normalUrl1.m_directory )) - return false; - - return true; - } - - internal String NormalizeUrl() - { - DoDeferredParse(); - StringBuilder builtUrl = StringBuilderCache.Acquire(); - - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0) - { -#if !PLATFORM_UNIX - builtUrl = builtUrl.AppendFormat("FILE:///{0}/{1}", m_localSite.ToString(), m_directory.ToString()); -#else - builtUrl = builtUrl.AppendFormat("FILE:///{0}", m_directory.ToString()); -#endif // !PLATFORM_UNIX - } - else - { - builtUrl = builtUrl.AppendFormat("{0}://{1}{2}", m_protocol, m_userpass, m_siteString.ToString()); - - if (m_port != -1) - builtUrl = builtUrl.AppendFormat("{0}",m_port); - - builtUrl = builtUrl.AppendFormat("/{0}", m_directory.ToString()); - } - - return StringBuilderCache.GetStringAndRelease(builtUrl).ToUpper(CultureInfo.InvariantCulture); - } - -#if !PLATFORM_UNIX - internal URLString SpecialNormalizeUrl() - { - // Under WinXP, file protocol urls can be mapped to - // drives that aren't actually file protocol underneath - // due to drive mounting. This code attempts to figure - // out what a drive is mounted to and create the - // url is maps to. - - DoDeferredParse(); - if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0) - { - return this; - } - else - { - String localSite = m_localSite.ToString(); - - if (localSite.Length == 2 && - (localSite[1] == '|' || - localSite[1] == ':')) - { - String deviceName = null; - GetDeviceName(localSite, JitHelpers.GetStringHandleOnStack(ref deviceName)); - - if (deviceName != null) - { - if (deviceName.IndexOf( "://", StringComparison.Ordinal ) != -1) - { - URLString u = new URLString( deviceName + "/" + this.m_directory.ToString() ); - u.DoDeferredParse(); // Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL - return u; - } - else - { - URLString u = new URLString( "file://" + deviceName + "/" + this.m_directory.ToString() ); - u.DoDeferredParse();// Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL - return u; - } - } - else - return this; - } - else - { - return this; - } - } - } - - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern void GetDeviceName( String driveLetter, StringHandleOnStack retDeviceName ); - -#else - internal URLString SpecialNormalizeUrl() - { - return this; - } -#endif // !PLATFORM_UNIX - - } - - - [Serializable] - internal class DirectoryString : SiteString - { - private bool m_checkForIllegalChars; - - private new static char[] m_separators = { '/' }; - - // From KB #Q177506, file/folder illegal characters are \ / : * ? " < > | - protected static char[] m_illegalDirectoryCharacters = { '\\', ':', '*', '?', '"', '<', '>', '|' }; - - public DirectoryString() - { - m_site = ""; - m_separatedSite = new ArrayList(); - } - - public DirectoryString( String directory, bool checkForIllegalChars ) - { - m_site = directory; - m_checkForIllegalChars = checkForIllegalChars; - m_separatedSite = CreateSeparatedString(directory); - } - - private ArrayList CreateSeparatedString(String directory) - { - if (directory == null || directory.Length == 0) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - Contract.EndContractBlock(); - - ArrayList list = new ArrayList(); - String[] separatedArray = directory.Split(m_separators); - - for (int index = 0; index < separatedArray.Length; ++index) - { - if (separatedArray[index] == null || separatedArray[index].Equals( "" )) - { - // this case is fine, we just ignore it the extra separators. - } - else if (separatedArray[index].Equals( "*" )) - { - if (index != separatedArray.Length-1) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - list.Add( separatedArray[index] ); - } - else if (m_checkForIllegalChars && separatedArray[index].IndexOfAny( m_illegalDirectoryCharacters ) != -1) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - else - { - list.Add( separatedArray[index] ); - } - } - - return list; - } - - public virtual bool IsSubsetOf( DirectoryString operand ) - { - return this.IsSubsetOf( operand, true ); - } - - public virtual bool IsSubsetOf( DirectoryString operand, bool ignoreCase ) - { - if (operand == null) - { - return false; - } - else if (operand.m_separatedSite.Count == 0) - { - return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; - } - else if (this.m_separatedSite.Count == 0) - { - return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; - } - else - { - return base.IsSubsetOf( operand, ignoreCase ); - } - } - } - -#if !PLATFORM_UNIX - [Serializable] - internal class LocalSiteString : SiteString - { - private new static char[] m_separators = { '/' }; - - public LocalSiteString( String site ) - { - m_site = site.Replace( '|', ':'); - - if (m_site.Length > 2 && m_site.IndexOf( ':' ) != -1) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - - m_separatedSite = CreateSeparatedString(m_site); - } - - private ArrayList CreateSeparatedString(String directory) - { - if (directory == null || directory.Length == 0) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - Contract.EndContractBlock(); - - ArrayList list = new ArrayList(); - String[] separatedArray = directory.Split(m_separators); - - for (int index = 0; index < separatedArray.Length; ++index) - { - if (separatedArray[index] == null || separatedArray[index].Equals( "" )) - { - if (index < 2 && - directory[index] == '/') - { - list.Add( "//" ); - } - else if (index != separatedArray.Length-1) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - } - else if (separatedArray[index].Equals( "*" )) - { - if (index != separatedArray.Length-1) - { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl")); - } - list.Add( separatedArray[index] ); - } - else - { - list.Add( separatedArray[index] ); - } - } - - return list; - } - - public virtual bool IsSubsetOf( LocalSiteString operand ) - { - return this.IsSubsetOf( operand, true ); - } - - public virtual bool IsSubsetOf( LocalSiteString operand, bool ignoreCase ) - { - if (operand == null) - { - return false; - } - else if (operand.m_separatedSite.Count == 0) - { - return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; - } - else if (this.m_separatedSite.Count == 0) - { - return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0; - } - else - { - return base.IsSubsetOf( operand, ignoreCase ); - } - } } -#endif // !PLATFORM_UNIX } diff --git a/src/mscorlib/src/System/Security/Util/XMLUtil.cs b/src/mscorlib/src/System/Security/Util/XMLUtil.cs deleted file mode 100644 index 3a1aaa3b09..0000000000 --- a/src/mscorlib/src/System/Security/Util/XMLUtil.cs +++ /dev/null @@ -1,435 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** PURPOSE: Helpers for XML input & output -** -===========================================================*/ -namespace System.Security.Util { - - using System; - using System.Security; - using System.Security.Permissions; - using System.Security.Policy; - using System.Runtime.InteropServices; - using System.Runtime.Remoting; - using System.IO; - using System.Text; - using System.Runtime.CompilerServices; - using PermissionState = System.Security.Permissions.PermissionState; - using BindingFlags = System.Reflection.BindingFlags; - using Assembly = System.Reflection.Assembly; - using System.Threading; - using System.Globalization; - using System.Reflection; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - internal static class XMLUtil - { - // - // Warning: Element constructors have side-effects on their - // third argument. - // - - private const String BuiltInPermission = "System.Security.Permissions."; - - public static SecurityElement - NewPermissionElement (IPermission ip) - { - return NewPermissionElement (ip.GetType ().FullName) ; - } - - public static SecurityElement - NewPermissionElement (String name) - { - SecurityElement ecr = new SecurityElement( "Permission" ); - ecr.AddAttribute( "class", name ); - return ecr; - } - - public static void - AddClassAttribute( SecurityElement element, Type type, String typename ) - { - // Replace any quotes with apostrophes so that we can include quoted materials - // within classnames. Notably the assembly name member 'loc' uses a quoted string. - - // NOTE: this makes assumptions as to what reflection is expecting for a type string - // it will need to be updated if reflection changes what it wants. - - if ( typename == null ) - typename = type.FullName; - Debug.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName); - element.AddAttribute( "class", typename + ", " + type.Module.Assembly.FullName.Replace( '\"', '\'' ) ); - } - - internal static bool ParseElementForAssemblyIdentification(SecurityElement el, - out String className, - out String assemblyName, // for example "WindowsBase" - out String assemblyVersion) - { - - className = null; - assemblyName = null; - assemblyVersion = null; - - String fullClassName = el.Attribute( "class" ); - - if (fullClassName == null) - { - return false; - } - if (fullClassName.IndexOf('\'') >= 0) - { - fullClassName = fullClassName.Replace( '\'', '\"' ); - } - - int commaIndex = fullClassName.IndexOf( ',' ); - int namespaceClassNameLength; - - // If the classname is tagged with assembly information, find where - // the assembly information begins. - - if (commaIndex == -1) - { - return false; - } - - namespaceClassNameLength = commaIndex; - className = fullClassName.Substring(0, namespaceClassNameLength); - String assemblyFullName = fullClassName.Substring(commaIndex + 1); - AssemblyName an = new AssemblyName(assemblyFullName); - assemblyName = an.Name; - assemblyVersion = an.Version.ToString(); - return true; - } - private static bool - ParseElementForObjectCreation( SecurityElement el, - String requiredNamespace, - out String className, - out int classNameStart, - out int classNameLength ) - { - className = null; - classNameStart = 0; - classNameLength = 0; - - int requiredNamespaceLength = requiredNamespace.Length; - - String fullClassName = el.Attribute( "class" ); - - if (fullClassName == null) - { - throw new ArgumentException( Environment.GetResourceString( "Argument_NoClass" ) ); - } - - if (fullClassName.IndexOf('\'') >= 0) - { - fullClassName = fullClassName.Replace( '\'', '\"' ); - } - - if (!PermissionToken.IsMscorlibClassName( fullClassName )) - { - return false; - } - - int commaIndex = fullClassName.IndexOf( ',' ); - int namespaceClassNameLength; - - // If the classname is tagged with assembly information, find where - // the assembly information begins. - - if (commaIndex == -1) - { - namespaceClassNameLength = fullClassName.Length; - } - else - { - namespaceClassNameLength = commaIndex; - } - - // Only if the length of the class name is greater than the namespace info - // on our requiredNamespace do we continue - // with our check. - - if (namespaceClassNameLength > requiredNamespaceLength) - { - // Make sure we are in the required namespace. - if (fullClassName.StartsWith(requiredNamespace, StringComparison.Ordinal)) - { - className = fullClassName; - classNameLength = namespaceClassNameLength - requiredNamespaceLength; - classNameStart = requiredNamespaceLength; - return true; - } - } - - return false; - } - - public static IPermission - CreatePermission (SecurityElement el, PermissionState permState, bool ignoreTypeLoadFailures) - { - if (el == null || !(el.Tag.Equals("Permission") || el.Tag.Equals("IPermission")) ) - throw new ArgumentException( String.Format( null, Environment.GetResourceString( "Argument_WrongElementType" ), "<Permission>" ) ) ; - Contract.EndContractBlock(); - - String className; - int classNameLength; - int classNameStart; - - if (!ParseElementForObjectCreation( el, - BuiltInPermission, - out className, - out classNameStart, - out classNameLength )) - { - goto USEREFLECTION; - } - - // We have a built in permission, figure out which it is. - - // UIPermission - // FileIOPermission - // SecurityPermission - // PrincipalPermission - // ReflectionPermission - // FileDialogPermission - // EnvironmentPermission - // GacIdentityPermission - // UrlIdentityPermission - // SiteIdentityPermission - // ZoneIdentityPermission - // KeyContainerPermission - // UnsafeForHostPermission - // HostProtectionPermission - // StrongNameIdentityPermission - // RegistryPermission - // PublisherIdentityPermission - - switch (classNameLength) - { - case 12: - // UIPermission - if (String.Compare(className, classNameStart, "UIPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new UIPermission( permState ); - else - goto USEREFLECTION; - - case 16: - // FileIOPermission - if (String.Compare(className, classNameStart, "FileIOPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new FileIOPermission( permState ); - else - goto USEREFLECTION; - - case 18: - // RegistryPermission - // SecurityPermission - if (className[classNameStart] == 'R') - { - if (String.Compare(className, classNameStart, "RegistryPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new RegistryPermission( permState ); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "SecurityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new SecurityPermission( permState ); - else - goto USEREFLECTION; - } - case 20: - // ReflectionPermission - // FileDialogPermission - if (className[classNameStart] == 'R') - { - if (String.Compare(className, classNameStart, "ReflectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new ReflectionPermission( permState ); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "FileDialogPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new FileDialogPermission( permState ); - else - goto USEREFLECTION; - } - - case 21: - // EnvironmentPermission - // UrlIdentityPermission - // GacIdentityPermission - if (className[classNameStart] == 'E') - { - if (String.Compare(className, classNameStart, "EnvironmentPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new EnvironmentPermission( permState ); - else - goto USEREFLECTION; - } - else if (className[classNameStart] == 'U') - { - if (String.Compare(className, classNameStart, "UrlIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new UrlIdentityPermission( permState ); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "GacIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new GacIdentityPermission( permState ); - else - goto USEREFLECTION; - } - case 22: - // SiteIdentityPermission - // ZoneIdentityPermission - // KeyContainerPermission - if (className[classNameStart] == 'S') - { - if (String.Compare(className, classNameStart, "SiteIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new SiteIdentityPermission( permState ); - else - goto USEREFLECTION; - } - else if (className[classNameStart] == 'Z') - { - if (String.Compare(className, classNameStart, "ZoneIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new ZoneIdentityPermission( permState ); - else - goto USEREFLECTION; - } - else - { - if (String.Compare(className, classNameStart, "KeyContainerPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new KeyContainerPermission( permState ); - else - goto USEREFLECTION; - } - case 24: - // HostProtectionPermission - if (String.Compare(className, classNameStart, "HostProtectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new HostProtectionPermission( permState ); - else - goto USEREFLECTION; - case 28: - // StrongNameIdentityPermission - if (String.Compare(className, classNameStart, "StrongNameIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) - return new StrongNameIdentityPermission( permState ); - else - goto USEREFLECTION; - default: - goto USEREFLECTION; - } - -USEREFLECTION: - - Object[] objs = new Object[1]; - objs[0] = permState; - - Type permClass = null; - IPermission perm = null; - - new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); - permClass = GetClassFromElement(el, ignoreTypeLoadFailures); - if (permClass == null) - return null; - if (!(typeof(IPermission).IsAssignableFrom(permClass))) - throw new ArgumentException( Environment.GetResourceString("Argument_NotAPermissionType") ); - - perm = (IPermission) Activator.CreateInstance(permClass, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, objs, null ); - - return perm; - } - - internal static Type - GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures) - { - String className = el.Attribute( "class" ); - - if (className == null) - { - if (ignoreTypeLoadFailures) - return null; - else - throw new ArgumentException( String.Format( null, Environment.GetResourceString("Argument_InvalidXMLMissingAttr"), "class") ); - } - - if (ignoreTypeLoadFailures) - { - try - { - return Type.GetType(className, false, false); - } - catch (SecurityException) - { - return null; - } - } - else - return Type.GetType(className, true, false); - } - - public static bool - IsPermissionElement (IPermission ip, - SecurityElement el) - { - if (!el.Tag.Equals ("Permission") && !el.Tag.Equals ("IPermission")) - return false; - - return true; - } - - public static bool - IsUnrestricted (SecurityElement el) - { - String sUnrestricted = el.Attribute( "Unrestricted" ); - - if (sUnrestricted == null) - return false; - - return sUnrestricted.Equals( "true" ) || sUnrestricted.Equals( "TRUE" ) || sUnrestricted.Equals( "True" ); - } - - - public static String BitFieldEnumToString( Type type, Object value ) - { - int iValue = (int)value; - - if (iValue == 0) - return Enum.GetName( type, 0 ); - - StringBuilder result = StringBuilderCache.Acquire(); - bool first = true; - int flag = 0x1; - - for (int i = 1; i < 32; ++i) - { - if ((flag & iValue) != 0) - { - String sFlag = Enum.GetName( type, flag ); - - if (sFlag == null) - continue; - - if (!first) - { - result.Append( ", " ); - } - - result.Append( sFlag ); - first = false; - } - - flag = flag << 1; - } - - return StringBuilderCache.GetStringAndRelease(result); - } - } -} diff --git a/src/mscorlib/src/System/Security/Util/sitestring.cs b/src/mscorlib/src/System/Security/Util/sitestring.cs deleted file mode 100644 index 28f23742ec..0000000000 --- a/src/mscorlib/src/System/Security/Util/sitestring.cs +++ /dev/null @@ -1,289 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Security.Util { - using System; - using System.Collections; - using System.Globalization; - using System.Diagnostics.Contracts; - - [Serializable] - internal class SiteString - { - protected String m_site; - protected ArrayList m_separatedSite; - - protected static char[] m_separators = { '.' }; - - protected internal SiteString() - { - // Only call this in derived classes when you know what you're doing. - } - - public SiteString( String site ) - { - m_separatedSite = CreateSeparatedSite( site ); - m_site = site; - } - - private SiteString(String site, ArrayList separatedSite) - { - m_separatedSite = separatedSite; - m_site = site; - } - - private static ArrayList CreateSeparatedSite(String site) - { - if (site == null || site.Length == 0) - { - throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); - } - Contract.EndContractBlock(); - - ArrayList list = new ArrayList(); - int braIndex = -1; - int ketIndex = -1; - braIndex = site.IndexOf('['); - if (braIndex == 0) - ketIndex = site.IndexOf(']', braIndex+1); - - if (ketIndex != -1) - { - // Found an IPv6 address. Special case that - String ipv6Addr = site.Substring(braIndex+1, ketIndex-braIndex-1); - list.Add(ipv6Addr); - return list; - } - - // Regular hostnames or IPv4 addresses - // We dont need to do this for IPv4 addresses, but it's easier to do it anyway - String[] separatedArray = site.Split( m_separators ); - - for (int index = separatedArray.Length-1; index > -1; --index) - { - if (separatedArray[index] == null) - { - throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); - } - else if (separatedArray[index].Equals( "" )) - { - if (index != separatedArray.Length-1) - { - throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); - } - } - else if (separatedArray[index].Equals( "*" )) - { - if (index != 0) - { - throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); - } - list.Add( separatedArray[index] ); - } - else if (!AllLegalCharacters( separatedArray[index] )) - { - throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" )); - } - else - { - list.Add( separatedArray[index] ); - } - } - - return list; - } - - // KB# Q188997 - http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q188997& gives the list of allowed characters in - // a NETBIOS name. DNS names are a subset of that (alphanumeric or '-'). - private static bool AllLegalCharacters( String str ) - { - for (int i = 0; i < str.Length; ++i) - { - char c = str[i]; - - if (IsLegalDNSChar(c) || - IsNetbiosSplChar(c)) - { - continue; - } - else - { - return false; - } - } - - return true; - } - - private static bool IsLegalDNSChar(char c) - { - if ((c >= 'a' && c <= 'z') || - (c >= 'A' && c <= 'Z') || - (c >= '0' && c <= '9') || - (c == '-')) - return true; - else - return false; - } - private static bool IsNetbiosSplChar(char c) - { - // ! @ # $ % ^ & ( ) - _ ' { } . ~ are OK - switch (c) { - case '-': - case '_': - case '@': - case '!': - case '#': - case '$': - case '%': - case '^': - case '&': - case '(': - case ')': - case '\'': - case '{': - case '}': - case '.': - case '~': - return true; - default: - return false; - } - } - - public override String ToString() - { - return m_site; - } - - public override bool Equals(Object o) - { - if (o == null || !(o is SiteString)) - return false; - else - return this.Equals( (SiteString)o, true ); - } - - public override int GetHashCode() - { - TextInfo info = CultureInfo.InvariantCulture.TextInfo; - - return info.GetCaseInsensitiveHashCode( this.m_site ); - } - - internal bool Equals( SiteString ss, bool ignoreCase ) - { - if (this.m_site == null) - return ss.m_site == null; - if (ss.m_site == null) - return false; - return this.IsSubsetOf(ss, ignoreCase) && ss.IsSubsetOf(this, ignoreCase); - } - - - public virtual SiteString Copy() - { - return new SiteString( m_site, m_separatedSite ); - } - - public virtual bool IsSubsetOf( SiteString operand ) - { - return this.IsSubsetOf( operand, true ); - } - - public virtual bool IsSubsetOf( SiteString operand, bool ignoreCase ) - { - StringComparison strComp = (ignoreCase? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); - if (operand == null) - { - return false; - } - else if (this.m_separatedSite.Count == operand.m_separatedSite.Count && - this.m_separatedSite.Count == 0) - { - return true; - } - else if (this.m_separatedSite.Count < operand.m_separatedSite.Count - 1) - { - return false; - } - else if (this.m_separatedSite.Count > operand.m_separatedSite.Count && - operand.m_separatedSite.Count > 0 && - !operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*")) - { - return false; - } - else if (String.Compare( this.m_site, operand.m_site, strComp) == 0) - { - return true; - } - - for (int index = 0; index < operand.m_separatedSite.Count - 1; ++index) - { - if (String.Compare((String)this.m_separatedSite[index], (String)operand.m_separatedSite[index], strComp) != 0) - { - return false; - } - } - - if (this.m_separatedSite.Count < operand.m_separatedSite.Count) - { - return operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*"); - } - else if (this.m_separatedSite.Count == operand.m_separatedSite.Count) - { - // last item must be the same or operand must have a * in its last item - return (String.Compare((String)this.m_separatedSite[this.m_separatedSite.Count - 1], - (String)operand.m_separatedSite[this.m_separatedSite.Count - 1], - strComp ) == 0 || - operand.m_separatedSite[operand.m_separatedSite.Count - 1].Equals("*")); - - } - else - return true; - } - - - - public virtual SiteString Intersect( SiteString operand ) - { - if (operand == null) - { - return null; - } - else if (this.IsSubsetOf( operand )) - { - return this.Copy(); - } - else if (operand.IsSubsetOf( this )) - { - return operand.Copy(); - } - else - { - return null; - } - } - - public virtual SiteString Union( SiteString operand ) - { - if (operand == null) - { - return this; - } - else if (this.IsSubsetOf( operand )) - { - return operand.Copy(); - } - else if (operand.IsSubsetOf( this )) - { - return this.Copy(); - } - else - { - return null; - } - } - } -} |