using System;
using System.IO;
using System.Reflection;
using System.Text;
using Vinno.FIS.Sonopost.Wireless.Win32.Interop;
namespace Vinno.FIS.Sonopost.Wireless
{
internal static class ProfileFactory
{
///
/// Generates the profile XML for the access point and password
///
internal static string Generate(WlanAvailableNetwork network, string password)
{
string profile = string.Empty;
string template = string.Empty;
string name = Encoding.UTF8.GetString(network.dot11Ssid.SSID, 0, (int)network.dot11Ssid.SSIDLength);
string hex = GetHexString(network.dot11Ssid.SSID);
var authAlgo = network.dot11DefaultAuthAlgorithm;
switch (network.dot11DefaultCipherAlgorithm)
{
case Dot11CipherAlgorithm.None:
template = GetTemplate("OPEN");
profile = string.Format(template, name, hex);
break;
case Dot11CipherAlgorithm.WEP:
template = GetTemplate("WEP");
profile = string.Format(template, name, hex, password);
break;
case Dot11CipherAlgorithm.CCMP:
if (authAlgo == Dot11AuthAlgorithm.RSNA)
{
template = GetTemplate("WPA2-Enterprise-PEAP-MSCHAPv2");
profile = string.Format(template, name);
}
else // PSK
{
template = GetTemplate("WPA2-PSK");
profile = string.Format(template, name, password);
}
break;
case Dot11CipherAlgorithm.TKIP:
#warning Robin: Not sure WPA uses RSNA
if (authAlgo == Dot11AuthAlgorithm.RSNA)
{
template = GetTemplate("WPA-Enterprise-PEAP-MSCHAPv2");
profile = string.Format(template, name);
}
else // PSK
{
template = GetTemplate("WPA-PSK");
profile = string.Format(template, name, password);
}
break;
default:
throw new NotImplementedException("Profile for selected cipher algorithm is not implemented");
}
return profile;
}
///
/// Fetches the template for an wireless connection profile.
///
private static string GetTemplate(string name)
{
var projectName = Assembly.GetExecutingAssembly().GetName().Name.ToString();
string resourceName = $"{projectName}.ProfileXML.{name}.xml";
using (StreamReader reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)))
{
return reader.ReadToEnd();
}
}
///
/// Converts an byte array into the hex representation, ex: [255, 255] -> "FFFF"
///
private static string GetHexString(byte[] ba)
{
StringBuilder sb = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
if (b == 0)
break;
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
}
}