コード例 #1
0
        /// <summary>
        /// Removes the "Allow" read permissions, and adds the "Deny" read permission
        /// on the HOSTS file. If the Hosts file cannot be locked, the exception error
        /// will be logged in the App error log
        /// </summary>
        public bool Lock()
        {
            // Make sure we have a security object
            if (Security == null)
            {
                return(false);
            }

            // Donot allow Read for the Everyone Sid. This prevents the BF2 client from reading the hosts file
            Security.RemoveAccessRule(new FileSystemAccessRule(WorldSid, FileSystemRights.ReadData, AccessControlType.Allow));
            Security.AddAccessRule(new FileSystemAccessRule(WorldSid, FileSystemRights.ReadData, AccessControlType.Deny));

            // Try and set the new access control
            try
            {
                HostFile.SetAccessControl(Security);
                IsLocked = true;
                return(true);
            }
            catch (Exception e)
            {
                TraceLog.TraceError("Unable to REMOVE the Readonly rule on Hosts File: " + e.Message);
                LastException = e;
                return(false);
            }
        }
コード例 #2
0
        /// <summary>
        /// Removes the "Deny" read permissions, and adds the "Allow" read permission
        /// on the HOSTS file. If the Hosts file cannot be unlocked, the exception error
        /// will be logged in the App error log
        /// </summary>
        public bool UnLock()
        {
            // Make sure we have a security object
            if (Security == null)
            {
                return(false);
            }

            // Allow ReadData
            Security.RemoveAccessRule(new FileSystemAccessRule(WorldSid, FileSystemRights.ReadData, AccessControlType.Deny));
            Security.AddAccessRule(new FileSystemAccessRule(WorldSid, FileSystemRights.ReadData, AccessControlType.Allow));

            // Try and set the new access control
            try
            {
                HostFile.SetAccessControl(Security);
                IsLocked = false;
                return(true);
            }
            catch (Exception e)
            {
                TraceLog.TraceError("Unable to REMOVE the Readonly rule on Hosts File: " + e.Message);
                LastException = e;
                return(false);
            }
        }
コード例 #3
0
        /// <summary>
        /// Generates a trace log for an exception. If an exception is thrown here, The error
        /// will automatically be logged in the programs error log
        /// </summary>
        /// <param name="FileName">The tracelog filepath (Must not exist yet)</param>
        /// <param name="E">The exception to log</param>
        public static void GenerateExceptionLog(string FileName, Exception E)
        {
            // Try to write to the log
            try
            {
                // Generate the tracelog
                using (StreamWriter Log = new StreamWriter(File.Open(FileName, FileMode.Create, FileAccess.Write)))
                {
                    // Write the header data
                    Log.WriteLine("-------- BF2Statistics Exception Trace Log --------");
                    Log.WriteLine("Exception Date: " + DateTime.Now.ToString());
                    Log.WriteLine("Program Version: " + Program.Version.ToString());
                    Log.WriteLine("Os Version: " + Environment.OSVersion.VersionString);
                    Log.WriteLine("Environment Type: " + ((Environment.Is64BitOperatingSystem) ? "x64" : "x86"));
                    //Log.WriteLine("RunAs Admin: " + ((Program.IsAdministrator) ? "True" : "False"));
                    Log.WriteLine();
                    Log.WriteLine("-------- Exception --------");

                    // Log each exception
                    int i = 0;
                    while (true)
                    {
                        // Create a stack trace
                        StackTrace trace = new StackTrace(E, true);
                        StackFrame frame = trace.GetFrame(0);

                        // Log the current exception
                        Log.WriteLine("Type: " + E.GetType().FullName);
                        Log.WriteLine("Message: " + E.Message.Replace("\n", "\n\t"));
                        Log.WriteLine("Target Method: " + frame.GetMethod().Name);
                        Log.WriteLine("File: " + frame.GetFileName());
                        Log.WriteLine("Line: " + frame.GetFileLineNumber());
                        Log.WriteLine("StackTrace:");
                        Log.WriteLine(E.StackTrace.TrimEnd());

                        // If we have no more inner exceptions, end the logging
                        if (E.InnerException == null)
                        {
                            break;
                        }

                        // Prepare next inner exception data
                        Log.WriteLine();
                        Log.WriteLine("-------- Inner Exception ({0}) --------", i++);
                        E = E.InnerException;
                    }

                    Log.Flush();
                }
            }
            catch (Exception Ex)
            {
                TraceLog.TraceError("Unable to generate exception log!!! : " + Ex.ToString());
                throw;
            }
        }
コード例 #4
0
        public static void Load()
        {
            TraceLog.Write("Loading client settings... ");
            if (Container == null)
            {
                try
                {
                    using (FileStream file = File.Open(FilePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
                        using (StreamReader reader = new StreamReader(file))
                        {
                            string contents = reader.ReadToEnd();
                            if (String.IsNullOrWhiteSpace(contents))
                            {
                                Container = new SettingsContainer();
                            }
                            else
                            {
                                Container = JsonConvert.DeserializeObject <SettingsContainer>(contents);
                            }

                            TraceLog.WriteLine("Success!");
                        }
                }
                catch (Exception e)
                {
                    TraceLog.WriteLine("Failed!");
                    TraceLog.Indent();
                    TraceLog.TraceError(e.Message);
                    TraceLog.Unindent();
                    Container = new SettingsContainer();
                }

                // Ensure we have the default provider if none others
                if (Container.ServiceProviders.Count == 0)
                {
                    Container.AddDefaultProvider();

                    // Save changes
                    Save();
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Loads a battlefield 2 server into this object for use.
        /// </summary>
        /// <param name="Bf2Path">The full root path to the server's executable file</param>
        public static void SetInstallPath(string Bf2Path)
        {
            // Write trace
            TraceLog.WriteLine($"Loading Battlefield 2 directory: \"{Bf2Path}\"");
            TraceLog.Indent();

            // Make sure we have a valid server path
            if (!File.Exists(Path.Combine(Bf2Path, "bf2.exe")))
            {
                // Write trace
                TraceLog.TraceError("Invalid BF2 installation path. bf2.exe does not exist!");
                TraceLog.Unindent();
                throw new ArgumentException("Invalid BF2 installation path");
            }

            // Make sure we actually changed server paths before processing
            if (!String.IsNullOrEmpty(RootPath) && (new Uri(Bf2Path)) == (new Uri(RootPath)))
            {
                // Write trace
                TraceLog.WriteLine("Installation directory was not changed, aborting.");
                TraceLog.Unindent();

                // Same path is selected, just return
                return;
            }

            // Temporary variables
            string        Modpath  = Path.Combine(Bf2Path, "mods");
            List <BF2Mod> TempMods = new List <BF2Mod>();

            // Make sure the server has the required folders
            if (!Directory.Exists(Modpath))
            {
                // Write trace
                TraceLog.TraceError("Unable to locate the 'mods' folder.");
                TraceLog.Unindent();
                throw new Exception("Unable to locate the 'mods' folder. Please make sure you have selected a valid "
                                    + "battlefield 2 installation path before proceeding.");
            }

            // Load all found mods, discarding invalid mods
            ModLoadErrors = new List <string>();
            IEnumerable <string> ModList = from dir in Directory.GetDirectories(Modpath) select dir.Substring(Modpath.Length + 1);

            foreach (string Name in ModList)
            {
                try
                {
                    // Create a new instance of the mod, and store it for later
                    BF2Mod Mod = new BF2Mod(Modpath, Name);
                    TempMods.Add(Mod);
                    TraceLog.WriteLine("Loaded mod: " + Mod.Name);
                }
                catch (InvalidModException E)
                {
                    ModLoadErrors.Add(E.Message);
                    TraceLog.WriteLine($"Failed to Load mod: \"{Name}\" Error: {E.Message}");
                    continue;
                }
                catch (Exception E)
                {
                    ModLoadErrors.Add(E.Message);
                    TraceLog.TraceError($"Caught Exception loading mod: \"{Name}");
                    TraceLog.Indent();
                    TraceLog.WriteLine(E.Message);
                    TraceLog.Unindent();
                }
            }

            // We need mods bro...
            if (TempMods.Count == 0)
            {
                TraceLog.TraceError($"No valid mods could be found!");
                throw new Exception("No valid battlefield 2 mods could be found in the Bf2 Server mods folder!");
            }

            // Define var values after we now know this server apears valid
            RootPath = Bf2Path;
            Mods     = TempMods;
            TraceLog.Unindent();

            // Fire change event
            if (PathChanged != null)
            {
                PathChanged();
            }

            // Recheck server process
            CheckServerProcess();
        }
コード例 #6
0
        /// <summary>
        /// Creates a new instance of SysHostsFile
        /// </summary>
        public SysHostsFile() : base()
        {
            // We dont know?
            IsLocked = false;
            try
            {
                // Get the Hosts file object
                HostFile = new FileInfo(FilePath);

                // If HOSTS file is readonly, remove that attribute!
                if (HostFile.IsReadOnly)
                {
                    try
                    {
                        HostFile.IsReadOnly = false;
                    }
                    catch (Exception e)
                    {
                        TraceLog.TraceError("HOSTS file is READONLY, Attribute cannot be removed: " + e.Message);
                        LastException = e;
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                TraceLog.TraceError("Program cannot access HOSTS file in any way: " + e.Message);
                LastException = e;
                return;
            }

            // Try to get the Access Control for the hosts file
            try
            {
                Security = HostFile.GetAccessControl();
            }
            catch (Exception e)
            {
                TraceLog.TraceError("Unable to get HOSTS file Access Control: " + e.Message);
                LastException = e;
                return;
            }

            // Make sure we can read the file amd write to it!
            try
            {
                // Unlock hosts file
                if (!UnLock())
                {
                    return;
                }

                // Get the hosts file contents
                using (StreamReader Rdr = new StreamReader(HostFile.OpenRead()))
                {
                    while (!Rdr.EndOfStream)
                    {
                        OrigContents.Add(Rdr.ReadLine());
                    }
                }

                CanRead = true;
            }
            catch (Exception e)
            {
                TraceLog.TraceError("Unable to READ the HOSTS file: " + e.Message);
                LastException = e;
                return;
            }

            // Check that we can write to the hosts file
            try
            {
                using (FileStream Stream = HostFile.OpenWrite())
                    CanWrite = true;
            }
            catch (Exception e)
            {
                TraceLog.TraceError("Unable to WRITE to the HOSTS file: " + e.Message);
                LastException = e;
                return;
            }

            // Parse file entries
            base.ParseEntries();
        }
コード例 #7
0
        /// <summary>
        /// Creates a new instance of HostsFileIcs
        /// </summary>
        public HostsFileIcs() : base()
        {
            // We dont know?
            try
            {
                // Get the Hosts file object
                HostFile = new FileInfo(FilePath);

                // Make sure file exists
                if (!HostFile.Exists)
                {
                    HostFile.Open(FileMode.Create).Close();
                }

                // If HOSTS file is readonly, remove that attribute!
                if (HostFile.IsReadOnly)
                {
                    try
                    {
                        HostFile.IsReadOnly = false;
                    }
                    catch (Exception e)
                    {
                        TraceLog.TraceError("HOSTS.ics file is READONLY, Attribute cannot be removed: " + e.Message);
                        LastException = e;
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                TraceLog.TraceError("Program cannot access HOSTS.ics file in any way: " + e.Message);
                LastException = e;
                return;
            }

            // Make sure we can read the file amd write to it!
            try
            {
                // Get the hosts file contents
                using (StreamReader Rdr = new StreamReader(HostFile.OpenRead()))
                {
                    CanRead = true;
                    while (!Rdr.EndOfStream)
                    {
                        OrigContents.Add(Rdr.ReadLine());
                    }
                }
            }
            catch (Exception e)
            {
                TraceLog.TraceError("Unable to READ the HOSTS.ics file: " + e.Message);
                LastException = e;
                return;
            }

            // Check that we can write to the hosts file
            try
            {
                using (FileStream Stream = HostFile.OpenWrite())
                    CanWrite = true;
            }
            catch (Exception e)
            {
                TraceLog.TraceError("Unable to WRITE to the HOSTS.ics file: " + e.Message);
                LastException = e;
                return;
            }

            // Parse file entries
            base.ParseEntries();
        }
コード例 #8
0
        /// <summary>
        /// The main entry point for the redirector
        /// </summary>
        /// <returns>Returns wether the DNS cache results match the selected IPAddresses</returns>
        public static bool Initialize()
        {
            // Only initialize once
            if (!IsInitialized)
            {
                IsInitialized = true;
                TraceLog.WriteLine("Initializing Redirector");
                TraceLog.Indent();

                // Set the System.Net DNS Cache refresh timeout to 1 millisecond
                ServicePointManager.DnsRefreshTimeout = 1;

                // Get config options
                RedirectMethod = Program.Config.RedirectMode;
                TraceLog.WriteLine("Chosen Redirect mode: " + RedirectMethod.ToString());

                // Create new Instances
                HostsFileSys = new SysHostsFile();
                HostsFileIcs = new HostsFileIcs();

                // Detect redirects
                bool IcsHasRedirects   = HostsFileIcs.HasAnyEntry(GamespyHosts) || HostsFileIcs.HasEntry(Bf2StatsHost);
                bool HostsHasRedirects = HostsFileSys.HasAnyEntry(GamespyHosts) || HostsFileSys.HasEntry(Bf2StatsHost);

                // Write tracelogs
                TraceLog.WriteLine("System Hosts has redirects: " + ((HostsHasRedirects) ? "True" : "False"));
                TraceLog.WriteLine("Hosts.ics has redirects: " + ((IcsHasRedirects) ? "True" : "False"));

                // Both files cannot have redirects!
                if (IcsHasRedirects && HostsHasRedirects)
                {
                    // Get the Non-Selected mode, and remove those redirects
                    HostsFile toRemove = (RedirectMethod == RedirectMode.HostsFile)
                        ? HostsFileIcs as HostsFile
                        : HostsFileSys as HostsFile;

                    try
                    {
                        // Remove all redirects
                        TraceLog.Write("Removing redirects from unchosen hostsfile... ");
                        RemoveRedirects(toRemove);
                        TraceLog.WriteLine("Success");
                    }
                    catch (Exception e)
                    {
                        TraceLog.WriteLine("Failed!");
                        TraceLog.Indent();
                        TraceLog.TraceError(e.Message);
                    }
                }

                // Set old redirect data if we have it
                if (RedirectsEnabled)
                {
                    // Grab our service provider
                    ServiceProvider provider = ClientSettings.ServiceProviders
                                               .Where(x => x.Name == Program.Config.LastUsedProvider)
                                               .FirstOrDefault();

                    // Make sure we have an object before settings
                    if (provider != null)
                    {
                        SetProviderIPAddress(provider);
                    }
                }

                // Remove all indents
                TraceLog.Unindent(true);
            }

            // Verify cache
            return((RedirectsEnabled) ? VerifyDNSCache() : true);
        }