339 lines
12 KiB
C#

//----------------------------------------------------------------------------
//
// Copyright (c) Intel Corporation, 2011-2014 All Rights Reserved.
//
// File: Utils.cs
//
// Contents: High Level API: Utils.
//
// Notes:
//
//----------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Globalization;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Net.NetworkInformation;
using Intel.Manageability.Exceptions;
using System.Text;
namespace Intel.Manageability.Utils
{
class Utils
{
private const string PASSWORD_EXPRESSION = @"^(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{7,30}$";
#region Public Function
//The function get string and check if it is a valid IPv6.
public static bool ValidateIP6(string ip)
{
UriHostNameType tmpType = Uri.CheckHostName(ip);
if (tmpType == UriHostNameType.IPv6)
{
return true;
}
return false;
}
/// <summary>
/// Get information about the AMT machine.
/// </summary>
/// <returns>Information about the AMT machine, e.g. provisioning state, AMT version.</returns>
public static bool IsLocalHost(string host)
{
try
{
IPAddress parsedIPAddress;
// Check if the host name is local machine and get platform data by HECI.
// If the IP address is "127.0.0.1" (IPv4) or "::1" (IPv6), the address is of the local machine.
if (host == "127.0.0.1" || host == "::1" || host == "localhost")
{
return true;
}
// If the host name is a IP address
if (IPAddress.TryParse(host, out parsedIPAddress))
{
// Obtain a reference to all network interfaces in the machine.
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
IPInterfaceProperties ipProperties;
foreach (NetworkInterface networkInterface in networkInterfaces)
{
ipProperties = networkInterface.GetIPProperties();
foreach (IPAddressInformation unicastAddress in ipProperties.UnicastAddresses)
{
// If the machine name equals to one of the interface's IP Address.
if (unicastAddress.Address.ToString() == host)
{
return true;
}
}
}
}
else // If the host name is a FQDN - check if it is the local machine name.
{
if (host.Substring(0, host.IndexOf('.')).ToLower() == Environment.MachineName.ToLower())
{
return true;
}
}
return false;
}
catch (Exception ex)
{
throw new ManageabilityException("Failed to get host location. Failure reason: " + ex.Message);
}
}
public static bool ValidateFQDN(string fqdn)
{
//check for a '.'
bool dotExists = false;
for (int i = 0; i < fqdn.Length; i++)
{
char c = fqdn[i];
if ((c == '.'))
{
dotExists = true;
if (i >= fqdn.Length - 2)
return false;
continue;
}
if (!(LegalHostnameChar(c)))
return false;
if (i == (fqdn.Length - 1))
if (((c >= '0') && (c <= '9')) || (c == '.'))
return false;
}
if (!dotExists)
return false;
bool ret = Regex.IsMatch(fqdn, "(?=^.{1,254}$)(^(?:(?!\\d+\\.|-)[a-zA-Z0-9_#/\\-]{1,63}(?<!-)\\.?)+(?:[a-zA-Z]{2,})$)");
return ret;
}
public static bool ValidateIPv4(string ip)
{
if (string.IsNullOrEmpty(ip))
return false;
if (ip.CompareTo("0.0.0.0") == 0)
return false;
UriHostNameType tmpType = Uri.CheckHostName(ip);
if (tmpType == UriHostNameType.IPv4)
{
return true;
}
return false;
}
public static bool ValidateIPv6(string ip)
{
if (string.IsNullOrEmpty(ip))
return false;
UriHostNameType tmpType = Uri.CheckHostName(ip);
if (tmpType == UriHostNameType.IPv6)
{
return true;
}
return false;
}
public static bool ValidatePassword(string password)
{
return Regex.IsMatch(password, PASSWORD_EXPRESSION);
}
public static IPAddress GetNetworkForIP(IPAddress address, IPAddress subnetMask)
{
byte[] ipAdressInBytes = address.GetAddressBytes();
byte[] subnetMaskInBytes = subnetMask.GetAddressBytes();
if (ipAdressInBytes.Length != subnetMaskInBytes.Length)
throw new ManageabilityException("The IP length and subnet mask length must be much.");
byte[] broadcastAddress = new byte[ipAdressInBytes.Length];
for (int i = 0; i < ipAdressInBytes.Length; i++)
{
broadcastAddress[i] = (byte)(ipAdressInBytes[i] & subnetMaskInBytes[i]);
}
return new IPAddress(broadcastAddress);
}
public static bool CheckIfSameSubnet(IPAddress address2, IPAddress address1, IPAddress subnetMask)
{
IPAddress firstNetwork, seconNetwork;
try
{
firstNetwork = GetNetworkForIP(address2, subnetMask);
seconNetwork = GetNetworkForIP(address1, subnetMask);
}
catch (Exception)
{
return false;
}
return firstNetwork.Equals(seconNetwork);
}
public string ExtractIpFromConnectionAddress(string address)
{
string ipAddress = "";
if (address.StartsWith("https"))
{
ipAddress = address.Substring(8, address.Length - 8);
}
else if (address.StartsWith("http"))
{
ipAddress = address.Substring(7, address.Length - 7);
}
if (ipAddress.Contains(":"))
{
int index = ipAddress.LastIndexOf(":");
ipAddress = ipAddress.Substring(0, index);
}
//The IP address is an IPv6 type
if (ipAddress.Contains("["))
{
ipAddress = ipAddress.Substring(1, ipAddress.Length - 2);
}
return ipAddress;
}
public static int CompareVersions(string amtversion, string version)
{
try
{
Version amtVersion = new Version(amtversion);
Version versionToCopmare = new Version(version);
return amtVersion.CompareTo(versionToCopmare);
}
catch (Exception)
{
throw new ManageabilityException("Failed to compare versions. Check if the versions are in a correct format.");
}
}
public static byte[] ConvertStringToByteArray(string s)
{
char[] cArr = s.ToCharArray();
byte[] bArr = new byte[cArr.Length];
for (int i = 0; i < cArr.Length; i++)
{
bArr[i] = Convert.ToByte(cArr[i]);
}
return bArr;
}
public static string ConvertByteArrayToString(byte[] bytes)
{
StringBuilder str = new StringBuilder();
int index = 0;
for (index = 0; index < bytes.Length;)
str.Append((bytes[index].ToString("X").Length == 1) ? "0" + bytes[index++].ToString("X") : bytes[index++].ToString("X"));
return str.ToString();
}
public static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
if (a1 == null ^ a2 == null) return false;
if (ReferenceEquals(a1, a2)) return true;
if (a1.Length != a2.Length)
return false;
for (int i = 0; i < a1.Length; i++)
if (a1[i] != a2[i])
return false;
return true;
}
/// <summary>
/// Prior to Release 5.1 platformGUID return half of the numbers reversed.
/// this function return the GUID in correct format
/// Converts string with 32 contiguous digits GUID format into a 16 length byte array
/// </summary>
/// <param name="guidString">String with 32 contiguous digits GUID format</param>
/// <returns>A 16 length byte array representing the given string</returns>
public static byte[] ConvertGuidStringToByteArray(string guidString)
{
string newGuid = guidString.Replace("-", "");
byte[] guidByteArray = new byte[newGuid.Length / 2];
for (int i = 0; i < guidByteArray.Length; i++)
{
Byte.TryParse(
newGuid.Substring((i * 2), 2),
NumberStyles.AllowHexSpecifier,
null,
out guidByteArray[i]);
}
return guidByteArray;
}
//get description of value of enum and return the correct value in the enum
public static object ConvertStringToEnumValue(string value, Type enumType)
{
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
if (ConvertEnumValueToString((Enum)Enum.Parse(enumType, name)).Equals(value))
{
return Enum.Parse(enumType, name);
}
}
throw new ManageabilityException("Failed to convert the value to " + enumType.Name);
}
//get value of enum and return its description
public static string ConvertEnumValueToString(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
public static string ExtractAddressFromWsmanConnection(string connectionAddress)
{
string cutAdd = connectionAddress.StartsWith("https://") ? connectionAddress.Substring(8, connectionAddress.Length - 8) :
connectionAddress.Substring(7, connectionAddress.Length - 7);
return cutAdd.Substring(0, cutAdd.LastIndexOf(':'));
}
#endregion
#region Private function
private static bool LegalHostnameChar(char c)
{
if ((c >= 'a' && c <= 'z') || ((c >= 'A' && c <= 'Z')) || ((c >= '0' && c <= '9')))
{
return true;
}
if ((c == '-') || (c == '_') || (c == '/') || (c == '#'))
{
return true;
}
return false;
}
#endregion
}
public static class HLAPIExtentions
{
public static string ToStringAMTFormat(this Version version)
{
return new Version(version.Major, version.Minor, version.Revision, version.Build).ToString();// change the order as needed
}
}
}