Beispiel #1
0
        private static void DownloadExtractUpdate()
        {
            var distrZipFile = AppFolders.TempDir + "\\_distr.zip";

            File.Delete(distrZipFile);
            using (WebClient webClient = new WebClient())
            {
                try
                {
                    webClient.ForceBasicAuth(Settings2.Instance.UserID, _hardwareID);
                    var distrFile = webClient.UploadData(_updateFileURL, "POST", Encoding.UTF8.GetBytes("get-update-package"));
                    File.WriteAllBytes(distrZipFile, distrFile);
                    log.Info("Packages are downloaded!");
                }
                catch (Exception ex)
                {
                    log.Error("Can't download packages: " + ex.Message);
                    return;
                }
            }
            var updateDirectoryInfo = new DirectoryInfo(DistrDirectory);

            if (updateDirectoryInfo.Exists)
            {
                updateDirectoryInfo.Delete(true);
            }
            updateDirectoryInfo.Create();
            try
            {
                using (ZipFile zip = new ZipFile(distrZipFile, Encoding.UTF8))
                {
                    zip.Password = "******";
                    zip.ExtractAll(DistrDirectory, ExtractExistingFileAction.OverwriteSilently);
                }
                log.Info("Package <distr> is extracted to " + DistrDirectory);
            }
            catch (Exception ex)
            {
                log.Error("Can't extract <distr> package: " + ex.Message);
                return;
            }
            var updaterExe = new DirectoryInfo(DistrDirectory).GetFileSystemInfos().Where(l => l is FileInfo).Cast <FileInfo>().FirstOrDefault(info => info.Extension == ".exe");

            if (updaterExe == null)
            {
                log.Error("Can't find updater executable! Files: " + string.Join(", ", new DirectoryInfo(AppFolders.TempDir).GetFileSystemInfos().Where(l => l is FileInfo).Cast <FileInfo>().Select(l => l.Name)));
                return;
            }

            if (WoWProcessManager.Processes.Count > 0)
            {
                WoWProcessManager.WoWProcessClosed += WoWProcessManager_WoWProcessClosed;
                Notify.TrayPopup("Update for AxTools is ready", "AxTools can't update itself while WoW is running. You will be prompted to update as soon as you close all running WoW clients", NotifyUserType.Info, false, null, 60);
                log.Info("WoW client is running, waiting...");
            }
            else
            {
                NotifyAboutUpdate();
            }
        }
Beispiel #2
0
        public static WoWUIFrame GetFrameByName(GameInterface game, string name)
        {
            var stopwatch = Stopwatch.StartNew();

            if (!cachedFrames.TryGetValue(game.wowProcess.ProcessID, out ConcurrentDictionary <string, IntPtr> dict))
            {
                dict = (cachedFrames[game.wowProcess.ProcessID] = new ConcurrentDictionary <string, IntPtr>());
            }
            WoWUIFrame frame;

            if (dict.TryGetValue(name, out IntPtr address))
            {
                try
                {
                    frame = new WoWUIFrame(address, game.wowProcess);
                    if (frame.GetName == name)
                    {
                        return(frame);
                    }
                }
                catch { /* frame is moved in memory, ignore this exception and just rebuild the cache */ }
            }
            frame = GetAllFrames(game).FirstOrDefault(l => l.GetName == name);
            if (stopwatch.ElapsedMilliseconds > 500)
            {
                log.Error($"GetFrameByName exec time: {stopwatch.ElapsedMilliseconds}ms");
            }
            return(frame);
        }
Beispiel #3
0
 internal static void DeployArchive(string path)
 {
     IsRunning = true;
     IsRunningChanged?.Invoke(true);
     try
     {
         if (Directory.Exists(_settings.WoWDirectory))
         {
             if (File.Exists(path))
             {
                 log.Info("Deploying archive: " + path);
                 Unzip(path);
                 log.Info("Archive is deployed: " + path);
             }
             else
             {
                 log.Info("Archive " + path + " isn't found");
                 Notify.TrayPopup("Backup error", "Archive " + path + " isn't found", NotifyUserType.Error, true);
             }
         }
         else
         {
             log.Info("WoW dir (" + _settings.WoWDirectory + ") isn't found");
             Notify.TrayPopup("Backup error", "WoW dir (" + _settings.WoWDirectory + ") isn't found", NotifyUserType.Error, true);
         }
     }
     catch (Exception ex)
     {
         log.Error("Deploying error: " + ex.Message);
         Notify.TrayPopup("Deploying error", ex.Message, NotifyUserType.Error, true);
     }
     IsRunningChanged?.Invoke(false);
     IsRunning = false;
 }
Beispiel #4
0
 internal string GetLogin()
 {
     try
     {
         return(Encoding.UTF8.GetString(ProtectedData.Unprotect(EncryptedLogin, null, DataProtectionScope.CurrentUser)));
     }
     catch (Exception ex)
     {
         log.Error($"Exception is thrown in GetLogin(): {ex.Message}");
         return(null);
     }
 }
Beispiel #5
0
 private static void WoWProcessManager_WoWProcessClosed(int obj)
 {
     if (instanses.ContainsKey(obj))
     {
         WoWAntiKick wak = instanses[obj];
         instanses.Remove(obj);
         wak.Dispose();
     }
     else
     {
         logger.Error($"{nameof(WoWProcessManager_WoWProcessClosed)}: cannot find instance for process with id:{obj}");
     }
 }
Beispiel #6
0
 private static void ProcessWatcher_ProcessExited(ProcessManagerEvent obj)
 {
     try
     {
         if (obj.ProcessName.ToLower() == "wow.exe")
         {
             if (Processes.TryRemove(obj.ProcessId, out WowProcess pWowProcess))
             {
                 pWowProcess.Dispose();
                 log.Info($"{pWowProcess} Process closed, {Processes.Count} total");
                 OnWowProcessStopped();
                 WoWProcessStartedOrClosed?.Invoke();
                 WoWProcessClosed?.Invoke(obj.ProcessId);
             }
             else
             {
                 string name = obj.ProcessName.Substring(0, obj.ProcessName.Length - 4);
                 log.Error($"[{name}:{obj.ProcessId}] Closed WoW process not found");
             }
         }
     }
     catch (Exception ex)
     {
         log.Error($"[{obj.ProcessName}:{obj.ProcessId}] Process stopped with error: {ex.Message}");
     }
 }
Beispiel #7
0
 private void LinkSendLogToDev_Click(object sender, EventArgs e)
 {
     try
     {
         string subject = InputBox.Input("Any comment? (optional)", settings.StyleColor);
         if (subject != null)
         {
             WaitingOverlay waitingOverlay = new WaitingOverlay(this, "Please wait...", settings.StyleColor).Show();
             Task.Factory.StartNew(() =>
             {
                 try
                 {
                     Log2.UploadLog(subject);
                 }
                 catch (Exception ex)
                 {
                     log.Error("Can't send log: " + ex.Message);
                     this.TaskDialog("Can't send log", ex.Message, NotifyUserType.Error);
                 }
                 finally
                 {
                     BeginInvoke(new Action(waitingOverlay.Close));
                 }
             });
         }
     }
     catch (Exception ex)
     {
         log.Info("Can't send log file: " + ex.Message);
         this.TaskDialog("Log file sending error", ex.Message, NotifyUserType.Error);
     }
 }
        public DedicatedClient(string source, IPEndPoint ip)
        {
            string[]      parts = source.Split('\\');
            List <string> keys  = new List <string>();
            List <string> vals  = new List <string>();

            for (int i = 1; i < parts.Length; i++)
            {
                if (i % 2 == 1)
                {
                    keys.Add(parts[i]);
                }
                else
                {
                    vals.Add(parts[i]);
                }
            }
            if (keys.Count == vals.Count)
            {
                for (int i = 0; i < keys.Count; i++)
                {
                    Configuration.Add(keys[i], vals[i]);
                }
            }
            else
            {
                Log2.Error("Couldn't properly parse client info.");
            }
            IP      = ip;
            IP.Port = (int)ChanllegeServer.SwapShort(BitConverter.GetBytes((short)IP.Port));
        }
Beispiel #9
0
        private void EnterCredentialsASAP()
        {
            var counter = 300;

            while (counter > 0)
            {
                try
                {
                    process.Refresh();
                    if (process.MainWindowHandle != (IntPtr)0)
                    {
                        if (WoWProcessManager.Processes.TryGetValue(process.Id, out WowProcess wowProcess) && wowProcess.Memory != null)
                        {
                            bool okay;
                            if (wowProcess.IsValidBuild)
                            {
                                GlueState glueState     = wowProcess.Memory.Read <GlueState>(wowProcess.Memory.ImageBase + WowBuildInfoX64.GlueState);
                                var       focusedWidget = wowProcess.Memory.Read <IntPtr>(wowProcess.Memory.ImageBase + WowBuildInfoX64.FocusedWidget);
                                okay = glueState == GlueState.Disconnected && focusedWidget != (IntPtr)0;
                            }
                            else
                            {
                                Thread.Sleep(3000);
                                okay = true;
                            }
                            if (okay)
                            {
                                foreach (char ch in wowAccount.GetLogin())
                                {
                                    NativeMethods.PostMessage(wowProcess.MainWindowHandle, Win32Consts.WM_CHAR, (IntPtr)ch, IntPtr.Zero);
                                    Thread.Sleep(5);
                                }
                                var tabCode = new IntPtr(0x09);
                                NativeMethods.PostMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYDOWN, tabCode, IntPtr.Zero);
                                NativeMethods.PostMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYUP, tabCode, IntPtr.Zero);
                                Thread.Sleep(5);
                                foreach (char ch in wowAccount.GetPassword())
                                {
                                    NativeMethods.PostMessage(wowProcess.MainWindowHandle, Win32Consts.WM_CHAR, (IntPtr)ch, IntPtr.Zero);
                                    Thread.Sleep(5);
                                }
                                var enterCode = new IntPtr(0x0D);
                                NativeMethods.PostMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYDOWN, enterCode, IntPtr.Zero);
                                NativeMethods.PostMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYUP, enterCode, IntPtr.Zero);
                                log.Info($"{wowProcess} Credendials have been entered [{Utils.SecureString(wowAccount.GetLogin())}]");
                                break;
                            }
                        }
                    }
                    Thread.Sleep(100);
                    counter--;
                }
                catch (Exception ex)
                {
                    log.Error($"[{process.ProcessName}:{process.Id}] Internal error: {ex.Message}");
                }
            }
        }
Beispiel #10
0
 internal static void AddPluginToRunning(IPlugin3 plugin, WowProcess process)
 {
     lock (AddRemoveLock)
     {
         if (!RunningPlugins.Contains(plugin))
         {
             _pluginContainers.First(l => l.Plugin.GetType() == plugin.GetType()).IsRunning = true;
             try
             {
                 plugin.OnStart(new GameInterface(process));
                 PluginWoW[plugin.Name] = process.ProcessID;
                 PluginsUsageStats[plugin.Name].Add(DateTime.UtcNow);
                 SavePluginUsageStats();
                 log.Info($"{process} [{plugin.Name}] Plug-in is started");
             }
             catch (Exception ex)
             {
                 log.Error($"Plug-in OnStart error [{plugin.Name}]: {ex.Message}");
             }
             Notify.TrayPopup(nameof(AxTools), "Plug-in <" + plugin.Name + "> is started", NotifyUserType.Info, false, plugin.TrayIcon);
             PluginStateChanged?.Invoke(plugin);
         }
     }
 }
Beispiel #11
0
 private void SaveToDB(string name)
 {
     lock (dbLock)
     {
         if (dbConnection == null)
         {
             dbConnection = new SQLiteConnection($"Data Source={AppFolders.DataDir}\\players.sqlite;Version=3;").OpenAndReturn();
         }
         using (SQLiteCommand command = new SQLiteCommand(dbConnection))
         {
             command.CommandText = "CREATE TABLE IF NOT EXISTS players ( guid TEXT NOT NULL, name TEXT NOT NULL );" +
                                   $"INSERT INTO players (guid, name) values ('{GUID}', '{name.Replace("'", "''")}')";
             try
             {
                 command.ExecuteNonQuery();
             }
             catch (Exception ex)
             {
                 log.Error("[SaveToDB] Error-0: " + ex.Message +
                           $"\r\nINSERT INTO players (guid, name) values ('{GUID}', '{name.Replace("'", "''")}')");
             }
         }
     }
 }
Beispiel #12
0
        private static bool TryGetSavedOffsets(byte[] hash)
        {
            Log2   log          = new Log2(nameof(WowBuildInfoX64));
            string hashAsString = BitConverter.ToString(hash);
            var    directory    = Directory.CreateDirectory(Path.Combine(AppFolders.DataDir, "wow-builds"));
            var    filePath     = Path.Combine(directory.FullName, hashAsString + ".json");

            log.Info($"TryGetSavedOffsets: filepath: '{filePath}'");
            if (File.Exists(filePath))
            {
                log.Info($"TryGetSavedOffsets: file exists, trying to deserialize...");
                try
                {
                    var offsets = JsonConvert.DeserializeObject <Dictionary <string, IntPtr> >(File.ReadAllText(filePath, Encoding.UTF8));
                    if (offsets.Count == patterns.Length)
                    {
                        log.Info("TryGetSavedOffsets: deserialization is successful!");
                        WoWHash             = hash;
                        BlackMarketNumItems = offsets[nameof(BlackMarketNumItems)].ToInt32();
                        BlackMarketItems    = offsets[nameof(BlackMarketItems)].ToInt32();
                        LastHardwareAction  = offsets[nameof(LastHardwareAction)].ToInt32();
                        TickCount           = offsets[nameof(TickCount)].ToInt32();
                        MouseoverGUID       = offsets[nameof(MouseoverGUID)].ToInt32();
                        ChatIsOpened        = offsets[nameof(ChatIsOpened)].ToInt32();
                        FocusedWidget       = offsets[nameof(FocusedWidget)].ToInt32();
                        ObjectManager       = offsets[nameof(ObjectManager)].ToInt32();
                        GlueState           = offsets[nameof(GlueState)].ToInt32();
                        GameState           = offsets[nameof(GameState)].ToInt32();
                        KnownSpellsCount    = offsets[nameof(KnownSpellsCount)].ToInt32();
                        KnownSpells         = offsets[nameof(KnownSpells)].ToInt32();
                        UIFrameBase         = offsets[nameof(UIFrameBase)].ToInt32();
                        PlayerZoneID        = offsets[nameof(PlayerZoneID)].ToInt32();
                        PlayerIsLooting     = offsets[nameof(PlayerIsLooting)].ToInt32();
                        PlayerGUID          = offsets[nameof(PlayerGUID)].ToInt32();
                        NotLoadingScreen    = offsets[nameof(NotLoadingScreen)].ToInt32();
                        IsChatAFK           = offsets[nameof(IsChatAFK)].ToInt32();
                        ChatBuffer          = offsets[nameof(ChatBuffer)].ToInt32();
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    log.Error($"TryGetSavedOffsets: deserialization is failed: {ex.Message}");
                }
            }
            return(false);
        }
Beispiel #13
0
 public override bool Execute()
 {
     // In more advanced cases we can override the Execute method as well.
     // We can perform additional checks, or even entirely bypass weaving
     // by not calling the base Execute method.
     if (new Random().Next(0, 10) == 11)
     {
         // Log2 is a property introduced in MSBuildWeaver.
         // It exposes a Serilog ILogger that logs any event to MSBuild.
         // An error raised either by Log2 or Log will fail the build
         // if the base Execute method is called.
         Log2.Error("Sorry, something went wrong with the laws of math :-(");
         return(false);
     }
     // Calling the base method will eventually call the DoWeave method below.
     return(base.Execute());
 }
Beispiel #14
0
 private void Loop()
 {
     while (flag)
     {
         balancingStopwatch.Restart();
         if (info.IsInGame)
         {
             try
             {
                 action();
             }
             catch (Exception ex)
             {
                 log.Error($"[{PluginName ?? ""}] SafeTimer error: {ex.Message}");
             }
         }
         var shouldWait = (int)(interval - balancingStopwatch.ElapsedMilliseconds);
         while (shouldWait > 0 && flag)
         {
             Thread.Sleep(Math.Min(shouldWait, 100));
             shouldWait = (int)(interval - balancingStopwatch.ElapsedMilliseconds);
         }
     }
 }
Beispiel #15
0
        private static void Zip()
        {
            Log2 vssLog = new Log2(nameof(AddonsBackup) + " - VSS Service");
            // get free drive letter
            string driveLetter = new string[] { "P:", "Q:", "R:", "S:", "T:", "U:", "V:", "W:" }.FirstOrDefault(l => !DriveInfo.GetDrives().Select(m => m.RootDirectory.Name).Contains(l));

            if (driveLetter == default(string))
            {
                throw new IOException("Can't find free drive letter!");
            }
            vssLog.Info($"Free drive letter: {driveLetter}");
            // making VSS snapshot
            IVssImplementation   vssImplementation = VssUtils.LoadImplementation();
            IVssBackupComponents backupComponents  = vssImplementation.CreateVssBackupComponents();

            backupComponents.InitializeForBackup(null);
            vssLog.Info("VssBackupComponents is initialized");
            Guid backupGuid1 = Guid.Empty;

            try
            {
                backupComponents.GatherWriterMetadata();
                backupComponents.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease);
                backupComponents.SetBackupState(false, true, VssBackupType.Full, false);
                vssLog.Info("VssBackupComponents is set up");
                backupComponents.StartSnapshotSet();
                backupGuid1 = backupComponents.AddToSnapshotSet(new DirectoryInfo(_settings.WoWDirectory).Root.Name, Guid.Empty);
                backupComponents.PrepareForBackup();
                backupComponents.DoSnapshotSet();
                vssLog.Info("Snapshot is taken");
                backupComponents.ExposeSnapshot(backupGuid1, null, VssVolumeSnapshotAttributes.ExposedLocally, driveLetter);
                // zipping
                string zipPath = $"{_settings.WoWAddonsBackupPath}\\AddonsBackup_{DateTime.UtcNow:yyyyMMdd_HHmmss}.zip";
                log.Info("Zipping to file: " + zipPath);
                using (ZipFile zip = new ZipFile(zipPath, Encoding.UTF8))
                {
                    zip.CompressionLevel = (CompressionLevel)_settings.WoWAddonsBackupCompressionLevel;
                    foreach (string dirName in FoldersToArchive)
                    {
                        zip.AddDirectory(_settings.WoWDirectory.Replace(new DirectoryInfo(_settings.WoWDirectory).Root.Name, $"{driveLetter}\\") + "\\" + dirName, "\\" + dirName);
                    }
                    zip.SaveProgress += AddonsBackup_SaveProgress;
                    var processPriority = Process.GetCurrentProcess().PriorityClass;
                    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
                    zip.Save();
                    Process.GetCurrentProcess().PriorityClass = processPriority;
                    zip.SaveProgress -= AddonsBackup_SaveProgress;
                }
            }
            finally
            {
                VssSnapshotProperties existingSnapshot = backupComponents.QuerySnapshots().FirstOrDefault(l => l.SnapshotId == backupGuid1);
                if (existingSnapshot == default(VssSnapshotProperties))
                {
                    vssLog.Error($"Can't delete snapshot {backupGuid1}");
                }
                else
                {
                    backupComponents.DeleteSnapshot(existingSnapshot.SnapshotId, true);
                    backupComponents.Dispose();
                    vssLog.Info($"Snapshot is deleted ({existingSnapshot.SnapshotId})");
                }
                GC.Collect();
            }
        }
Beispiel #16
0
 internal void ChatboxSendText(string text, int attempts = 3)
 {
     if (text.Length <= 254) // 254 - max length of non-latin string in game chat box
     {
         lock (chatLocks[wowProcess.ProcessID])
         {
             wowProcess.WaitWhileWoWIsMinimized();
             if (IsInGame && !IsLoadingScreen)
             {
                 if (ChatIsOpened)
                 {
                     var vkLControl = (IntPtr)0xA2;
                     var vkA        = (IntPtr)0x41;
                     var vkDelete   = (IntPtr)0x2E;
                     NativeMethods.SendMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYDOWN, vkLControl, IntPtr.Zero);
                     NativeMethods.SendMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYDOWN, vkA, IntPtr.Zero);
                     NativeMethods.SendMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYUP, vkA, IntPtr.Zero);
                     NativeMethods.SendMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYUP, vkLControl, IntPtr.Zero);
                     NativeMethods.SendMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYDOWN, vkDelete, IntPtr.Zero);
                     NativeMethods.SendMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYUP, vkDelete, IntPtr.Zero);
                     Thread.Sleep(200);
                 }
                 else
                 {
                     var counter = 1000;
                     NativeMethods.SendMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYDOWN, (IntPtr)13, IntPtr.Zero);
                     NativeMethods.SendMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYUP, (IntPtr)13, IntPtr.Zero);
                     while (!ChatIsOpened && counter > 0)
                     {
                         counter -= 10;
                         Thread.Sleep(10);
                     }
                     Thread.Sleep(250);
                 }
                 foreach (char ch in text)
                 {
                     NativeMethods.PostMessage(wowProcess.MainWindowHandle, Win32Consts.WM_CHAR, (IntPtr)ch, IntPtr.Zero);
                 }
                 string editboxText = null;
                 Thread.Sleep(100);
                 for (int i = 0; i < 10; i++)
                 {
                     if ((editboxText = GetEditboxText()) == text)
                     {
                         NativeMethods.SendMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYDOWN, (IntPtr)13, IntPtr.Zero);
                         NativeMethods.SendMessage(wowProcess.MainWindowHandle, Win32Consts.WM_KEYUP, (IntPtr)13, IntPtr.Zero);
                         return;
                     }
                     Thread.Sleep(100);
                 }
                 attempts--;
                 if (attempts > 0)
                 {
                     log.Info($"ChatboxSendText: recursive call, attempts: {attempts}");
                     ChatboxSendText(text, attempts);
                 }
                 else
                 {
                     log.Error($"ChatboxSendText: text and editboxText are not equal; text: {text}; editboxText: {editboxText}");
                     Notify.TrayPopup("Can't send command via chat", "Please don't type while this bot is working", NotifyUserType.Warn, true);
                 }
             }
         }
     }
     else
     {
         log.Error($"ChatboxSendText: string is too long (length={text.Length}): {text}");
     }
 }
Beispiel #17
0
 public static void LogError(this IPlugin3 plugin, object text)
 {
     log.Error($"[Plug-in: {plugin.Name}] {text}");
 }