public static Task<bool> ApplyRedirectsAsync(IProgress<TaskStep> Progress)
{
return Task.Run(() =>
{
// Remove old settings
if (RedirectsEnabled) RemoveRedirects();
// Invalid on no IP addresses
if (StatsServerAddress == null && GamespyServerAddress == null)
return false;
// Set new desired addresses
if (StatsServerAddress != null)
Program.Config.LastStatsServerAddress = StatsServerAddress.ToString();
if (GamespyServerAddress != null)
Program.Config.LastLoginServerAddress = GamespyServerAddress.ToString();
Program.Config.Save();
// Can't do anything with a dns server
if (RedirectMethod == RedirectMode.DnsServer) return true;
// === Apply new settings === //
// Grab hosts file base
HostsFile hFile = (RedirectMethod == RedirectMode.HostsFile)
? HostsFileSys as HostsFile
: HostsFileIcs as HostsFile;
// Unlock system hosts file
if (RedirectMethod == RedirectMode.HostsFile)
{
// Make sure file is writable
if (SysHostsFile.IsLocked && !HostsFileSys.UnLock())
{
Progress.Report(new TaskStep(0, "Cannot allow READ permissions on the Hosts File", true, hFile.LastException));
return false;
}
else
Progress.Report(new TaskStep(0, ""));
}
// Make sure file is writable
if (!hFile.CanRead)
{
Progress.Report(new TaskStep(1, "Cannot read the Hosts File", true, hFile.LastException));
return false;
}
else
Progress.Report(new TaskStep(1, ""));
// Make sure file is readable
if (!hFile.CanWrite)
{
Progress.Report(new TaskStep(2, "Cannot write to the Hosts File", true, hFile.LastException));
return false;
}
else
Progress.Report(new TaskStep(2, ""));
// ===== Set Redirect Addresses ===== //
// Stats Server
if (StatsServerAddress != null)
hFile.Set(Bf2StatsHost, StatsServerAddress);
// Gamespy Servers
if (GamespyServerAddress != null)
{
foreach (string hostname in GamespyHosts)
hFile.Set(hostname, GamespyServerAddress);
}
// Report Progress
Progress.Report(new TaskStep(3, "Gamespy Redirects Set"));
// ===== Save Redirects ===== //
int Step = 4;
string ErrDesc = "";
try
{
// Attempt to save the hosts file
ErrDesc = "Unable to Save Hosts File!";
hFile.Save();
// Report Success
Progress.Report(new TaskStep(Step++, "Hosts File Saved Successfully"));
// Rebuild the DNS Cache
ErrDesc = "Failed to Rebuild the DNS Cache";
RebuildDNSCache(CancellationToken.None);
// Report Success
Progress.Report(new TaskStep(Step++, "DNS Cache Rebuilt Successfully"));
}
catch (Exception e)
{
RemoveRedirects();
Progress.Report(new TaskStep(Step, ErrDesc, true, e));
return false;
}
// Lock system hosts File
if (RedirectMethod == RedirectMode.HostsFile)
{
if (!Program.Config.LockHostsFile)
{
// Report Success
Progress.Report(new TaskStep(Step++, ""));
return true;
}
else if (HostsFileSys.Lock())
{
// Report Success
Progress.Report(new TaskStep(Step++, "Hosts File Read Permissions Removed"));
return true;
}
else
{
// Report Error
Progress.Report(new TaskStep(Step++, "Cannot Remove Hosts File Read Permissions!",
true, HostsFileSys.LastException));
return true;
}
}
return true;
});
}