public override CommandFeedback Execute(string[] args) { string strSourceFolder = Environment.CurrentDirectory; if (args.Length > 1) { strSourceFolder = args[1]; } string strDestiny = args[2]; string strPrefix = args[3]; List <string> filters = new List <string>(); for (int i = 4; i < args.Length; i++) { filters.Add(args[i]); } sourceFiles = new List <FileInfo>(); // scan all files from directory info ScanFolder(new DirectoryInfo(strDestiny), filters); RecursiveFolder(new DirectoryInfo(strSourceFolder), strDestiny, strPrefix, filters); ConsoleU.WriteLine("Total similar: " + similarCounter, ConsoleColor.Green); return(CommandFeedback.Success); }
static void RenameMutex(string procId, string[] mutexes) { ConsoleU.WriteLine($"Process ID {procId} request to rename mutexes", Palette.Wait); proc = Process.GetProcessById(int.Parse(procId)); ConsoleU.WriteLine($"Trying to rename mutexes {mutexes.Length} mutexes", Palette.Wait); for (int j = 0; j < mutexes.Length; j++) { string m = mutexes[j]; string prefix = $"({j + 1}/{mutexes.Length}) "; ConsoleU.WriteLine(prefix + "Trying to rename mutex: " + m, Palette.Feedback); for (; ;) { if (ProcessUtil.RenameMutex(proc, m)) { ConsoleU.WriteLine($"{prefix}Mutex rename {m}", Palette.Success); break; } else { ConsoleU.WriteLine($"{prefix}Mutex {m} could not be rename", Palette.Error); } Thread.Sleep(250); } } }
public override CommandFeedback Execute(string[] args) { if (args.Length == 1) { return(CommandFeedback.WrongNumberOfArguments); } string target = args[1]; string line = args[2]; string searchParams = args[3]; while (line.Contains("\\n")) { line = line.Replace("\\n", "\n"); } if (!Directory.Exists(target)) { return(CommandFeedback.Error); } ConsoleU.WriteLine("Searching directory...", Palette.Wait); // target is a directory DirectoryInfo dir = new DirectoryInfo(target); FileInfo[] files = dir.GetFiles(searchParams); ConsoleU.WriteLine($"Found { files.Length } files. Would you like to write to the top of them?", Palette.Question); int changed = 0; int failed = 0; if (consoleManager.InputYesNo()) { for (int i = 0; i < files.Length; i++) { FileInfo file = files[i]; try { string readAll = File.ReadAllText(file.FullName); readAll += line; File.Delete(file.FullName); File.WriteAllText(file.FullName, readAll); changed++; } catch { ConsoleU.WriteLine($"Failed writing to { file.Name } ", Palette.Error); failed++; } } } ConsoleU.WriteLine($"Changed { changed } files", Palette.Success); ConsoleU.WriteLine($"Failed to change { failed } files", failed == 0 ? Palette.Success : Palette.Error); ConsoleS.ReadLine(); return(CommandFeedback.Success); }
public override CommandFeedback Execute(string[] args) { if (args.Length == 1) { return(CommandFeedback.WrongNumberOfArguments); } string target = args[1]; if (!Path.IsPathRooted(target)) { // relative path string currentDir = Environment.CurrentDirectory; target = Path.Combine(currentDir, target); } if (!File.Exists(target)) { Console.WriteLine($"File not found: {target}"); return(CommandFeedback.Error); } // rename the source file to backup string dir = Path.GetDirectoryName(target); string fileName = Path.GetFileNameWithoutExtension(target); string sourceFile = Path.Combine(dir, fileName + "_Backup.m4a"); File.Move(target, sourceFile); string startArgs = $"ffmpeg -i \"{sourceFile}\" -acodec copy -movflags faststart \"{target}\""; int exitCode; CmdUtil.ExecuteCommand("", out exitCode, startArgs); bool makeBackup = false; if (File.Exists(target)) { if (!makeBackup) { File.Delete(sourceFile); } ConsoleU.WriteLine($"Okay", Palette.Success); } else { ConsoleU.WriteLine($"FFMPEG failed with code {exitCode}", Palette.Error); return(CommandFeedback.Error); } return(CommandFeedback.Success); }
public override CommandFeedback Execute(string[] args) { if (args.Length == 1) { return(CommandFeedback.WrongNumberOfArguments); } string target = args[1]; if (Directory.Exists(target)) { ConsoleU.WriteLine("Searching directory...", Palette.Wait); // target is a directory DirectoryInfo dir = new DirectoryInfo(target); List <string> dirs = new List <string>(); RecursiveSearch(dir, dirs); if (dirs.Count == 0) { ConsoleU.WriteLine($"Nothing to delete", Palette.Feedback); return(CommandFeedback.Success); } ConsoleU.WriteLine($"Found { dirs.Count } empty directories. Would you like to delete them?", Palette.Question); int deleted = 0; int failed = 0; if (consoleManager.InputYesNo()) { for (int i = 0; i < dirs.Count; i++) { string directory = dirs[i]; try { Directory.Delete(directory); deleted++; } catch { ConsoleU.WriteLine($"Failed deleting { directory } ", Palette.Error); failed++; } } } ConsoleU.WriteLine($"Deleted { deleted } files", Palette.Success); ConsoleU.WriteLine($"Failed to delete { failed } files", failed == 0 ? Palette.Success : Palette.Error); } else { // target is a file/doesnt exist } return(CommandFeedback.Success); }
public override CommandFeedback Execute(string[] args) { if (args.Length == 1) { return(CommandFeedback.WrongNumberOfArguments); } string target = args[1]; if (!File.Exists(target)) { return(CommandFeedback.Error); } string startTime = args[2]; string cutDuration = args[3]; // rename the source file to backup string dir = Path.GetDirectoryName(target); string fileName = Path.GetFileNameWithoutExtension(target); string sourceFile = Path.Combine(dir, fileName + "_Backup.m4a"); File.Move(target, sourceFile); //ffmpeg - ss 1:01:42 - i c:\Data\temp\in.m4a - vn - c copy - t 1:00:00 out.m4a //The first time(1:01:42) is the start time of the cut. //-vn means that only the audio stream is copied from the file. //The second time(1:00:00) is the duration of the cut.It can be longer then the length of the whole file. string startArgs = $"ffmpeg -ss {startTime} -i \"{sourceFile}\" -vn -c copy -t {cutDuration} \"{target}\""; int exitCode; CmdUtil.ExecuteCommand("", out exitCode, startArgs); bool makeBackup = false; if (File.Exists(target)) { if (!makeBackup) { File.Delete(sourceFile); } ConsoleU.WriteLine($"Okay", Palette.Success); } else { ConsoleU.WriteLine($"Failed", Palette.Error); } return(CommandFeedback.Success); }
public bool InputYesNo(bool silent = true) { ConsoleU.WriteLine("Yes/No", Palette.Question); if (silentMode) { // still shows up that we were asking the user a question ConsoleU.WriteLine(silent ? "Yes" : "No", Palette.Question); ConsoleU.WriteLine("yes"); return(silent); } string yesno = ConsoleU.ReadLine().ToLower(); return(yesno.StartsWith("y")); }
static void Main(string[] args) { ConsoleManager console = new ConsoleManager(); console.Init(); ConsoleU.WriteLine("DistroLucas's FileUtils v" + FileUtilsGlobals.DisplayVersion.ToString("F2", CultureInfo.InvariantCulture), ConsoleColor.White); console.SearchFromLoadedAssemblies(); if (args.Length > 0) { console.ExecuteCommand(args); } console.Run(); }
public void Run() { Console.WriteLine(); ConsoleU.WriteLine($"Server running in port {Port}", ConsoleColor.Cyan); string startFolder = AssemblyUtil.GetStartFolder(); ConsoleU.WriteLine($"Start folder: {startFolder}", ConsoleColor.Green); ConsoleU.WriteLine($"Path provided: {path}", ConsoleColor.Green); string[] files = Directory.GetFiles(path); for (int i = 0; i < files.Length; i++) { ConsoleU.WriteLine($"Files: {files[i]}", ConsoleColor.Green); } httpServer.Listen(); }
private void ServerThread(object state) { while (this.IsActive) { if (Debug) { TcpClient s = this.Listener.AcceptTcpClient(); Thread thread = new Thread(() => { if (DebugLock) { lock (DebugLocker) { this.Processor.HandleClient(s); } } else { this.Processor.HandleClient(s); } }); thread.Start(); Thread.Sleep(1); } else { try { TcpClient s = this.Listener.AcceptTcpClient(); Thread thread = new Thread(() => { try { this.Processor.HandleClient(s); } catch (Exception ex) { ConsoleU.WriteLine("Exception " + ex, ConsoleColor.Red); } }); thread.Start(); Thread.Sleep(1); } catch (Exception ex) { ConsoleU.WriteLine("Exception " + ex, ConsoleColor.Red); } } } }
public override CommandFeedback Execute(string[] args) { if (args.Length == 1) { ConsoleU.WriteLine(Help, Palette.Feedback); return(CommandFeedback.Success); } string target = args[1]; ConsoleCommand cmd = consoleManager.GetCommand(target); if (cmd != null) { ConsoleU.WriteLine(cmd.Help, Palette.Help); } else { ConsoleU.WriteLine("Unknown command", Palette.Error); } return(CommandFeedback.Success); }
static void StartGame(string path, string args = "", string workingDir = null) { if (!Path.IsPathRooted(path)) { string root = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); path = Path.Combine(root, path); } ProcessStartInfo startInfo; startInfo = new ProcessStartInfo(); startInfo.FileName = path; startInfo.Arguments = args; if (!string.IsNullOrWhiteSpace(workingDir)) { startInfo.WorkingDirectory = workingDir; } proc = Process.Start(startInfo); ConsoleU.WriteLine("Game started, process ID:" + proc.Id, Palette.Success); WriteToDataFile(path, proc.Id.ToString()); }
static void StartGame(string path, string args = "", string workingDir = null) { if (!Path.IsPathRooted(path)) { string root = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); path = Path.Combine(root, path); } int tri = 0; ProcessStartInfo startInfo; startInfo = new ProcessStartInfo(); startInfo.FileName = path; startInfo.Arguments = args; if (!string.IsNullOrWhiteSpace(workingDir)) { startInfo.WorkingDirectory = workingDir; } #if RELEASE try #endif { proc = Process.Start(startInfo); ConsoleU.WriteLine("Game started, process ID:" + proc.Id, Palette.Success); } #if RELEASE catch { tri++; if (tri < tries) { ConsoleU.WriteLine("Failed to start process. Retrying..."); StartGame(path, args); } } #endif }
public void ExecuteCommand(string[] sep) { if (sep.Length == 0) { return; } string first = sep[0]; ConsoleCommand cmd; if (!commands.TryGetValue(first, out cmd)) { ConsoleU.WriteLine("Unknown command", Palette.Error); return; } CommandFeedback feedback = cmd.Execute(sep); if (feedback != CommandFeedback.Success) { ConsoleU.WriteLine(feedback.ToString(), Palette.Error); } }
static void QueryMutex(string procId, string[] mutexes) { Log.WriteLine($"Process ID {procId} request to be queried for mutexes", Palette.Wait); proc = Process.GetProcessById(int.Parse(procId)); ConsoleU.WriteLine($"Trying to query for any mutex's existance", Palette.Wait); bool[] existence = new bool[mutexes.Length]; for (int j = 0; j < mutexes.Length; j++) { string m = mutexes[j]; string prefix = $"({j + 1}/{mutexes.Length}) "; ConsoleU.WriteLine($"{prefix}Trying to scan if mutex exists: {m}", Palette.Feedback); bool exists = ProcessUtil.MutexExists(proc, m); Log.WriteLine(exists); } Thread.Sleep(250); string json = JsonConvert.SerializeObject(existence); // no game path, save to startgame directory/Nucleus folder WriteToDataFile(Assembly.GetEntryAssembly().Location, json); }
static void Main(string[] args) { // We need this, else Windows will fake // all the data about monitors inside the application User32Util.SetProcessDpiAwareness(ProcessDPIAwareness.ProcessPerMonitorDPIAware); if (args.Length == 0) { ConsoleU.WriteLine("Invalid usage! Need arguments to proceed!", Palette.Error); return; } #if RELEASE try #endif { for (int i = 0; i < args.Length; i++) { string arg = args[i]; ConsoleU.WriteLine("Parsing line " + i + ": " + arg, Palette.Feedback); //Log(string.Format("Parsing line {0}: {1}", i, arg)); string argument = ""; for (int j = i; j < args.Length; j++) { string skey = args[j]; if (!skey.Contains("monitors") && !skey.Contains("game") && !skey.Contains("partialmutex") && !skey.Contains("mutextype") && !skey.Contains("mutex") && !skey.Contains("proc") && !skey.Contains("hook") && !skey.Contains("delay") && !skey.Contains("renamemutex") && !skey.Contains("mutextorename") && !skey.Contains("setwindow") && !skey.Contains("width") && !skey.Contains("height") && !skey.Contains("posx") && !skey.Contains("posy") && !skey.Contains("isdebug") && !skey.Contains("nucleusfolderpath") && !skey.Contains("blockraw") && !skey.Contains("nucenv") && !skey.Contains("playernick") && !skey.Contains("starthks") && !skey.Contains("root") && !skey.Contains("destination") && !skey.Contains("direxclusions") && !skey.Contains("fileexclusions") && !skey.Contains("filecopyinstead") && !skey.Contains("hardlink") && !skey.Contains("symfolder") && !skey.Contains("numplayers") && !skey.Contains("symlink") //&& !skey.Contains("rawhid") && !skey.Contains("createsingle") && !skey.Contains("rawhid") && !skey.Contains("docpath") && !skey.Contains("usedocs") && !skey.Contains("output")) { i++; if (string.IsNullOrEmpty(argument)) { argument = skey; } else { argument = argument + " " + skey; } } } //Log("Extra arguments:" + argument); ConsoleU.WriteLine("Extra arguments:" + argument, Palette.Feedback); string[] splited = (arg + argument).Split(new string[] { "|::|" }, StringSplitOptions.None); string key = splited[0].ToLower(); //Log("key " + key); if (key.Contains("monitors")) { } else if (key.Contains("hook")) { isHook = Boolean.Parse(splited[1]); } else if (key.Contains("delay")) { isDelay = Boolean.Parse(splited[1]); } else if (key.Contains("renamemutex")) { renameMutex = Boolean.Parse(splited[1]); } else if (key.Contains("mutextorename")) { mutexToRename = splited[1]; } else if (key.Contains("partialmutex")) { partialMutex = Boolean.Parse(splited[1]); } else if (key.Contains("setwindow")) { setWindow = Boolean.Parse(splited[1]); } else if (key.Contains("width")) { width = Int32.Parse(splited[1]); } else if (key.Contains("height")) { height = Int32.Parse(splited[1]); } else if (key.Contains("posx")) { posx = Int32.Parse(splited[1]); } else if (key.Contains("posy")) { posy = Int32.Parse(splited[1]); } else if (key.Contains("docpath")) { DocumentsRoot = splited[1]; } else if (key.Contains("usedocs")) { useDocs = Boolean.Parse(splited[1]); } else if (key.Contains("isdebug")) { isDebug = Boolean.Parse(splited[1]); } else if (key.Contains("nucleusfolderpath")) { nucleusFolderPath = splited[1]; } else if (key.Contains("blockraw")) { blockRaw = Boolean.Parse(splited[1]); } else if (key.Contains("createsingle")) { createSingle = Boolean.Parse(splited[1]); } else if (key.Contains("rawhid")) { rawHid = splited[1]; } else if (key.Contains("nucenv")) { useNucleusEnvironment = Boolean.Parse(splited[1]); } else if (key.Contains("playernick")) { playerNick = splited[1]; } else if (key.Contains("starthks")) { useStartupHooks = Boolean.Parse(splited[1]); } else if (key.Contains("root")) { root = splited[1]; } else if (key.Contains("currentdir")) { currentDir = splited[1]; } else if (key.Contains("destination")) { destination = splited[1].Substring(0, splited[1].LastIndexOf('\\')); } else if (key.Contains("direxclusions")) { dirExclusions = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None); } else if (key.Contains("fileexclusions")) { fileExclusions = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None); } else if (key.Contains("filecopyinstead")) { fileCopyInstead = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None); } else if (key.Contains("hardlink")) { hardLink = Boolean.Parse(splited[1]); } else if (key.Contains("symfolder")) { symFolders = Boolean.Parse(splited[1]); } else if (key.Contains("numplayers")) { numPlayers = int.Parse(splited[1]); } else if (key.Contains("symlink")) { int exitCode = 1; for (int p = 0; p < numPlayers; p++) { Nucleus.Gaming.Platform.Windows.IO.WinDirectoryUtil.LinkDirectory(root, new DirectoryInfo(root), destination + "\\Instance" + p, out exitCode, dirExclusions, fileExclusions, fileCopyInstead, hardLink, symFolders); } } //else if (key.Contains("rawhid")) //{ // rawHid = splited[1]; //} else if (key.Contains("game")) { string data = splited[1]; string[] subArgs = data.Split(';'); string path = subArgs[0]; string argu = null; if (subArgs.Length > 1) { argu = subArgs[1]; } string workingDir = null; if (path.Contains("|")) { string[] div = path.Split('|'); path = div[0]; workingDir = div[1]; } Log($"EXE: {path} ARGS: {argu} WORKDIR: {workingDir}"); ConsoleU.WriteLine($"Start game: EXE: {path} ARGS: {argu} WORKDIR: {workingDir}", Palette.Feedback); StartGame(path, argu, workingDir); } else if (key.Contains("mutextype")) { mt = splited[1]; } else if (key.Contains("mutex")) { string[] mutex = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None); ConsoleU.WriteLine("Trying to kill mutexes", Palette.Wait); for (int j = 0; j < mutex.Length; j++) { string m = mutex[j]; ConsoleU.WriteLine("Trying to kill mutex: " + m, Palette.Feedback); if (!ProcessUtil.KillMutex(proc, mt, m, partialMutex)) { ConsoleU.WriteLine("Mutex " + m + " could not be killed", Palette.Error); } else { ConsoleU.WriteLine("Mutex killed " + m, Palette.Success); } Thread.Sleep(150); } } else if (key.Contains("proc")) { string procId = splited[1]; int id = int.Parse(procId); try { proc = Process.GetProcessById(id); Log(string.Format($"Process ID {id} found!")); ConsoleU.WriteLine($"Process ID {id} found!", Palette.Success); } catch { Log(string.Format($"Process ID {id} not found")); ConsoleU.WriteLine($"Process ID {id} not found", Palette.Error); } } else if (key.Contains("output")) { string[] mutex = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None); bool all = true; for (int j = 0; j < mutex.Length; j++) { string m = mutex[j]; ConsoleU.WriteLine("Requested mutex: " + m, Palette.Error); bool exists = ProcessUtil.MutexExists(proc, mt, m, partialMutex); if (!exists) { all = false; } Thread.Sleep(500); } Console.WriteLine(all.ToString()); } } } #if RELEASE catch (Exception ex) { ConsoleU.WriteLine(ex.Message); } #endif }
static void StartGame(string path, string args = "", string workingDir = null) { System.IO.Stream str = new System.IO.MemoryStream(); //GenericGameInfo gen = new GenericGameInfo(null, null, str); bool regMethod = false; if (!Path.IsPathRooted(path)) { string root = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); path = Path.Combine(root, path); } try { //proc = Process.Start(startInfo); //string currDir = Directory.GetCurrentDirectory(); // This works even if the current directory is set elsewhere. string currDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //bool is64 = EasyHook.RemoteHooking.IsX64Process((int)pi.dwProcessId); //if (Is64Bit(path) == true) //{ // gameIs64 = true; //} //bool is64 = EasyHook.RemoteHooking.IsX64Process((int)pi.dwProcessId); IntPtr envPtr = IntPtr.Zero; uint pCreationFlags = 0; if (useNucleusEnvironment && !(useStartupHooks && (isHook || renameMutex || setWindow || blockRaw || createSingle))) { Log("Setting up Nucleus environment"); var sb = new StringBuilder(); IDictionary envVars = Environment.GetEnvironmentVariables(); //var username = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile).Replace(@"C:\Users\", ""); string username = WindowsIdentity.GetCurrent().Name.Split('\\')[1]; envVars["USERPROFILE"] = $@"{NucleusEnvironmentRoot}\NucleusCoop\{playerNick}"; envVars["HOMEPATH"] = $@"\Users\{username}\NucleusCoop\{playerNick}"; envVars["APPDATA"] = $@"{NucleusEnvironmentRoot}\NucleusCoop\{playerNick}\AppData\Roaming"; envVars["LOCALAPPDATA"] = $@"{NucleusEnvironmentRoot}\NucleusCoop\{playerNick}\AppData\Local"; //Some games will crash if the directories don't exist Directory.CreateDirectory($@"{NucleusEnvironmentRoot}\NucleusCoop"); Directory.CreateDirectory(envVars["USERPROFILE"].ToString()); Directory.CreateDirectory(Path.Combine(envVars["USERPROFILE"].ToString(), "Documents")); Directory.CreateDirectory(envVars["APPDATA"].ToString()); Directory.CreateDirectory(envVars["LOCALAPPDATA"].ToString()); Directory.CreateDirectory(Path.GetDirectoryName(DocumentsRoot) + $@"\NucleusCoop\{playerNick}\Documents"); if (useDocs) { if (!File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"utils\backup\User Shell Folders.reg"))) { //string mydocPath = key.GetValue("Personal").ToString(); ExportRegistry(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders", Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"utils\backup\User Shell Folders.reg")); } RegistryKey dkey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders", true); dkey.SetValue("Personal", Path.GetDirectoryName(DocumentsRoot) + $@"\NucleusCoop\{playerNick}\Documents", (RegistryValueKind)(int)RegType.ExpandString); } foreach (object envVarKey in envVars.Keys) { if (envVarKey != null) { string key = envVarKey.ToString(); string value = envVars[envVarKey].ToString(); sb.Append(key); sb.Append("="); sb.Append(value); sb.Append("\0"); } } sb.Append("\0"); byte[] envBytes = Encoding.Unicode.GetBytes(sb.ToString()); envPtr = Marshal.AllocHGlobal(envBytes.Length); Marshal.Copy(envBytes, 0, envPtr, envBytes.Length); } pCreationFlags += (uint)ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT; STARTUPINFO startup = new STARTUPINFO(); startup.cb = Marshal.SizeOf(startup); Thread.Sleep(1000); if (useStartupHooks && (isHook || renameMutex || setWindow || blockRaw || createSingle)) { Log("Starting game and injecting start up hooks via Nucleus.Inject"); bool?is64_n = Is64Bit(path); if (!is64_n.HasValue) { Log(string.Format("ERROR - Machine type {0} not implemented", GetDllMachineType(path))); return; } bool is64 = is64_n.Value; //PROCESS_INFORMATION procInfo = new PROCESS_INFORMATION(); Process[] gameProcs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(path)); bool alreadyExists = false; if (gameProcs.Length > 0) { foreach (Process gameProc in gameProcs) { if (gameProc.GetMainModuleFileName().ToLower() == path.ToLower()) { Log("Process with this path is already running! Skipping creating a new process"); pOutPID = (uint)gameProc.Id; alreadyExists = true; } } } if (!alreadyExists) { try { //if(useNucleusEnvironment) //{ // bool success = CreateProcess(null, path + " " + args, IntPtr.Zero, IntPtr.Zero, false, (uint)ProcessCreationFlags.CREATE_SUSPENDED | (uint)ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT, envPtr, Path.GetDirectoryName(path), ref startup, out PROCESS_INFORMATION processInformation); // if (!success) // { // Log(string.Format("ERROR - CreateProcess failed - startGamePath: {0}, startArgs: {1}, dirpath: {2}", path, args, Path.GetDirectoryName(path))); // return; // } // procInfo = processInformation; // pOutPID = (uint)processInformation.dwProcessId; //} //Thread.Sleep(1000); string injectorPath = Path.Combine(currDir, $"Nucleus.IJ{(is64 ? "x64" : "x86")}.exe"); ProcessStartInfo injstartInfo = new ProcessStartInfo(); injstartInfo.FileName = injectorPath; object[] injargs = new object[] { 0, // Tier 0 : start up hook path, // EXE path args, // Command line arguments. TODO: these args should be converted to base64 to prevent any special characters e.g. " breaking the injargs pCreationFlags, // Process creation flags 0, // InInjectionOptions (EasyHook) Path.Combine(currDir, "Nucleus.SHook32.dll"), // lib path 32 Path.Combine(currDir, "Nucleus.SHook64.dll"), // lib path 64 isHook, // Window hooks renameMutex, // Renames mutexes/semaphores/events hook mutexToRename, setWindow, // Set window hook isDebug, nucleusFolderPath, blockRaw, useNucleusEnvironment, playerNick, createSingle, rawHid, width, height, posx, posy, DocumentsRoot, useDocs }; var sbArgs = new StringBuilder(); foreach (object arg in injargs) { //Converting to base64 prevents characters like " or \ breaking the arguments string arg64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(arg.ToString())); sbArgs.Append(" \""); sbArgs.Append(arg64); sbArgs.Append("\""); } string arguments = sbArgs.ToString(); injstartInfo.Arguments = arguments; //injstartInfo.WindowStyle = ProcessWindowStyle.Hidden; //injstartInfo.CreateNoWindow = true; injstartInfo.UseShellExecute = false; injstartInfo.RedirectStandardOutput = true; injstartInfo.RedirectStandardInput = true; Process injectProc = Process.Start(injstartInfo); injectProc.OutputDataReceived += proc_OutputDataReceived; injectProc.BeginOutputReadLine(); injectProc.WaitForExit(); } catch (Exception ex) { Log(string.Format("ERROR - {0}", ex.Message)); } if (injectFailed) { injectFailed = false; throw new Exception("Failed to create and/or inject start up hook dll. " + tri + " of 2."); } //if(useNucleusEnvironment) //{ // ResumeThread(procInfo.hThread); //} Thread.Sleep(1000); } } else // regular method (no hooks) { Log("Starting game via regular process start method (no start up hooks enabled)"); bool success = CreateProcess(null, path + " " + args, IntPtr.Zero, IntPtr.Zero, false, (uint)ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT, envPtr, Path.GetDirectoryName(path), ref startup, out PROCESS_INFORMATION processInformation); if (!success) { Log(string.Format("ERROR - CreateProcess failed - startGamePath: {0}, startArgs: {1}, dirpath: {2}", path, args, Path.GetDirectoryName(path))); return; } pOutPID = (uint)processInformation.dwProcessId; proc = Process.GetProcessById((int)pOutPID); //pOutPID = proc.Id; regMethod = true; } Thread.Sleep(1000); while (pOutPID == 0) { Thread.Sleep(50); } bool isRunning = Process.GetProcesses().Any(x => x.Id == (int)pOutPID); bool foundProc = false; if (!isRunning || (isRunning && Process.GetProcessById((int)pOutPID).ProcessName.ToLower() != Path.GetFileNameWithoutExtension(path).ToLower())) { if (isRunning) { Log("Process ID " + pOutPID + " exists but does not match expected process name. Attempting to resolve."); } else { Log("Process ID " + pOutPID + " doesn't currently exist. Seeing if there is a process running by its path"); } Process[] gameProcs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(path)); if (gameProcs.Length > 0) { foreach (Process gameProc in gameProcs) { if (gameProc.GetMainModuleFileName().ToLower() == path.ToLower()) { Log("Process ID changed to " + pOutPID); foundProc = true; isRunning = true; pOutPID = (uint)gameProc.Id; } } if (!foundProc) { Log("Could not find process by its path"); } } else { Log("Could not find any matching process names"); } } else { Log("Process ID: " + pOutPID); if (Process.GetProcessById((int)pOutPID).GetMainModuleFileName().ToLower() == path.ToLower()) { foundProc = true; isRunning = true; } } //Thread.Sleep(100); //if (proc != null && proc.Threads[0].ThreadState != System.Diagnostics.ThreadState.Running) if (!isRunning && !foundProc) { Log("Process with ID " + pOutPID + " is still not currently running. Checking every 50 miliseconds for 10 seconds to see if process is running yet."); for (int times = 0; times < 200; times++) { Thread.Sleep(50); isRunning = Process.GetProcesses().Any(x => x.Id == (int)pOutPID); if (isRunning) { Log("Attempt #" + times + " - Process is now running"); proc = Process.GetProcessById((int)pOutPID); break; } if (times == 199 && !isRunning) { Log(string.Format("ERROR - Process with an id of {0} is not running after 10 seconds. Aborting.", pOutPID)); throw new Exception(string.Format("ERROR - Process with an id of {0} is not running after 10 seconds. Aborting.", pOutPID)); } } } ConsoleU.WriteLine("Game started, process ID:" + pOutPID /*Marshal.ReadInt32(pid)*/ /*proc.Id*/ /*(int)pi.dwProcessId*/, Palette.Success); if (isDebug) { //if (regMethod) //{ //Thread.Sleep(100); Log(string.Format("Game started, process ID: {0}", pOutPID)); //} //else //{ // Thread.Sleep(100); // Log(string.Format("Game started, process ID: {0}", pOutPID)); //} } } catch (Exception ex) { tri++; if (tri < tries) { if (!ex.Message.Contains("debug-log")) { Log(string.Format("ERROR - Failed to start process. EXCEPTION: {0} STACKTRACE: {1}", ex.Message, ex.StackTrace)); Console.WriteLine("Failed to start process. Retrying..."); } StartGame(path, args); } else { MessageBox.Show("Nucleus was unable to launch and/or find the proper process for this instance. Please close Nucleus and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public override void Write(string value) { ConsoleU.WriteLine(value); }
public override CommandFeedback Execute(string[] args) { string strSourceFolder = Environment.CurrentDirectory; if (args.Length > 1) { strSourceFolder = args[1]; } string strFilter = args[2]; sourceFiles = new List <FileInfo>(); ScanFolder(new DirectoryInfo(strSourceFolder), new List <string>() { strFilter }, sourceFiles); for (int i = 0; i < sourceFiles.Count; i++) { FileInfo file = sourceFiles[i]; string strFullName = file.FullName; string strFileText; using (Stream str = file.OpenRead()) { StreamReader strReader = new StreamReader(str); strFileText = strReader.ReadToEnd(); } int numClassIndex = strFileText.IndexOf("class"); int numNamespaceIndex = strFileText.IndexOf("namespace"); int numInsertIndex = 0; int numDefineIndex = strFileText.LastIndexOf("#define"); if (numDefineIndex != -1) { numInsertIndex = strFileText.IndexOf("\n", numDefineIndex + 1); } int numUsingIndex = strFileText.LastIndexOf("using"); if (numNamespaceIndex != -1) { int numUsingIndexEnd = 0; if (numUsingIndex != -1) { numUsingIndexEnd = strFileText.IndexOf(";", numUsingIndex); } ConsoleU.WriteLine($"File: {file.Name} already has namespace", ConsoleColor.Yellow); strFileText = strFileText.Insert(numInsertIndex, Environment.NewLine + "using PixelRipped1989;" + Environment.NewLine); //continue; } else { strFileText = strFileText.Insert(numInsertIndex, "namespace PixelRipped1989 {" + Environment.NewLine); int numLastBracket = strFileText.LastIndexOf("}"); strFileText = strFileText.Insert(strFileText.Length, Environment.NewLine + "}"); ConsoleU.WriteLine("File: " + file.Name, ConsoleColor.Green); } file.Delete(); File.WriteAllText(strFullName, strFileText); } return(CommandFeedback.Success); }
public override CommandFeedback Execute(string[] args) { string strSourceFolder = Environment.CurrentDirectory; if (args.Length > 1) { strSourceFolder = args[1]; } string strDestiny = args[2]; string strPrefix = args[3]; List <string> filters = new List <string>(); for (int i = 4; i < args.Length; i++) { filters.Add(args[i]); } sourceFiles = new List <FileInfo>(); destFiles = new List <FileInfo>(); updatedFiles = new List <FileInfo>(); renamedFiles = new Dictionary <FileInfo, string>(); // scan all files from directory info ScanFolder(new DirectoryInfo(strSourceFolder), filters, sourceFiles); ScanFolder(new DirectoryInfo(strDestiny), filters, destFiles); RecursiveFolder(new DirectoryInfo(strSourceFolder), strPrefix, filters); ConsoleU.WriteLine("Total similar: " + similarCounter, ConsoleColor.Green); for (int i = 0; i < updatedFiles.Count; i++) { FileInfo file = updatedFiles[i]; string strFullName = file.FullName; string strFileText; using (Stream str = file.OpenRead()) { StreamReader strReader = new StreamReader(str); strFileText = strReader.ReadToEnd(); } //file.Delete(); foreach (var filePair in renamedFiles) { FileInfo strLastFile = filePair.Key; string strLastName = Path.GetFileNameWithoutExtension(strLastFile.Name); string strNewName = filePair.Value; int numIndex = 0; for (; ;) { int newIndex = strFileText.IndexOf(strLastName, numIndex); if (newIndex == -1) { break; } int numEndIndex = strFileText.IndexOf(" ", newIndex); if (numEndIndex == -1) { numEndIndex = strFileText.IndexOf(".", newIndex); if (numEndIndex == -1) { continue; } } numIndex = numEndIndex + 1; int numActualStart = strFileText.Substring(0, newIndex).LastIndexOf(" "); int numEndPoint = strFileText.Substring(0, newIndex).LastIndexOf("."); if (numActualStart == -1) { numActualStart = numEndPoint; } else if (numEndPoint != -1) { // both have values numActualStart = Math.Max(numActualStart, numEndPoint); } numActualStart += 1; string strWord = strFileText.Substring(numActualStart, numEndIndex - numActualStart); if (strWord != strLastName) { continue; } int x = -1; referencesFound++; ConsoleU.WriteLine($"Rename {strLastName} to {strNewName}", ConsoleColor.Green); } } File.WriteAllText(strFullName, strFileText); } return(CommandFeedback.Success); }
private void ThreadCallback(object state) { ThreadData tData = (ThreadData)state; ConsoleU.WriteLine($"[{tData.ThreadID}] THREAD {tData.ThreadID} ON", ConsoleColor.Green, OutputLevel.Medium); for (; ;) { long startTime = Stopwatch.GetTimestamp(); ThreadTask task = GrabTask(startTime); if (task != null) { tData.CurrentTask = task; task.AssignThread(tData.ThreadID); // execute task task.Task(task); long endTime = Stopwatch.GetTimestamp(); bool doLog = false; double sElapsed = ((endTime - startTime) / (double)Stopwatch.Frequency) * 1000.0; if (sElapsed > MinTimeTaskLog) { doLog = true; ConsoleU.WriteLine($"[{tData.ThreadID}] TASK {task}", ConsoleColor.Green, OutputLevel.Medium); } // return to queued if its not finished if (!task.Finished) { bool printReturn = doLog; if (printReturn) { if (task.DependsOn.Length > 0) { string depends = ""; bool first = true; for (int i = 0; i < task.DependsOn.Length; i++) { ThreadTask depend = task.DependsOn[i]; string name = depend.Finished ? $"{depend.Name}(DONE)" : depend.Name; depends += !first ? (", " + name) : name; if (first) { first = false; } } if (task.NeedReexecution) { ConsoleU.WriteLine($"[{tData.ThreadID}] RET TASK: {task} FOR {depends} AND RE-EXECUTION ({task.ReexecutionMessage})", ConsoleColor.Yellow, OutputLevel.Medium); } else { ConsoleU.WriteLine($"[{tData.ThreadID}] RET TASK: {task} FOR {depends}", ConsoleColor.Yellow, OutputLevel.Medium); } } else if (task.NeedReexecution) { ConsoleU.WriteLine($"[{tData.ThreadID}] RET TASK: {task} FOR RE-EXECUTION ({task.ReexecutionMessage})", ConsoleColor.Yellow, OutputLevel.Medium); } else { ConsoleU.WriteLine($"[{tData.ThreadID}] RET TASK: {task} FOR UNKNOWN REASON", ConsoleColor.Red, OutputLevel.High); } } task.ResetToReexecute(); ReturnTask(task); } else { ConsoleU.WriteLine($"[{tData.ThreadID}] FINISH TASK: {task} ELAPSED: {(sElapsed / 1000.0)}s", ConsoleColor.Green, OutputLevel.Medium); } //tData.CurrentTask = null; // dont remove so we can read the last task } //Thread.Sleep(100); //Thread.Sleep(1);// 1ms sleep Thread.Sleep(TimeSpan.FromTicks(1));// 1 tick sleep if (finished) { break; } } }
static void StartGame(string path, string args = "", string workingDir = null) { System.IO.Stream str = new System.IO.MemoryStream(); GenericGameInfo gen = new GenericGameInfo(null, null, str); if (!Path.IsPathRooted(path)) { string root = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); path = Path.Combine(root, path); } int tri = 0; ProcessStartInfo startInfo; startInfo = new ProcessStartInfo(); startInfo.FileName = path; startInfo.Arguments = args; if (!string.IsNullOrWhiteSpace(workingDir)) { startInfo.WorkingDirectory = workingDir; } #if RELEASE try #endif { //proc = Process.Start(startInfo); string currDir = Directory.GetCurrentDirectory(); //bool is64 = EasyHook.RemoteHooking.IsX64Process((int)pi.dwProcessId); if (isHook || renameMutex || setWindow) { var targetsBytes = Encoding.Unicode.GetBytes(mutexToRename); int targetsBytesLength = targetsBytes.Length; int size = 7 + targetsBytesLength; var data = new byte[size]; data[0] = isHook == true ? (byte)1 : (byte)0; data[1] = renameMutex == true ? (byte)1 : (byte)0; data[2] = setWindow == true ? (byte)1 : (byte)0; data[3] = (byte)(targetsBytesLength >> 24); data[4] = (byte)(targetsBytesLength >> 16); data[5] = (byte)(targetsBytesLength >> 8); data[6] = (byte)targetsBytesLength; Array.Copy(targetsBytes, 0, data, 7, targetsBytesLength); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.Copy(data, 0, ptr, size); if (!isDelay) // CreateandInject method { if (Is64Bit(path) == true) { try { IntPtr pid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(uint))); RhCreateAndInject(path, args, 0, 0, Path.Combine(currDir, "Nucleus.SHook32.dll"), Path.Combine(currDir, "Nucleus.SHook64.dll"), ptr, (uint)size, pid); pOutPID = Marshal.ReadInt32(pid); Marshal.FreeHGlobal(pid); } catch (Exception ex) { using (StreamWriter writer = new StreamWriter("error-log.txt", true)) { writer.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + "ex msg: {0}, ex str: {1}", ex.Message, ex.ToString()); } } } else if (Is64Bit(path) == false) { try { //pidTest = gen.Inject(path, args, 0, 0, Path.Combine(currDir, "Nucleus.Hook32.dll"), null, IntPtr.Zero, 0); string injectorPath = Path.Combine(currDir, "Nucleus.Inject32.exe"); ProcessStartInfo injstartInfo = new ProcessStartInfo(); injstartInfo.FileName = injectorPath; object[] injargs = new object[] { 0, path, args, 0, 0, Path.Combine(currDir, "Nucleus.SHook32.dll"), null, isHook, renameMutex, mutexToRename, setWindow }; var sbArgs = new StringBuilder(); foreach (object arg in injargs) { sbArgs.Append(" \""); sbArgs.Append(arg); sbArgs.Append("\""); } string arguments = sbArgs.ToString(); injstartInfo.Arguments = arguments; //injstartInfo.WindowStyle = ProcessWindowStyle.Hidden; //injstartInfo.CreateNoWindow = true; injstartInfo.UseShellExecute = false; injstartInfo.RedirectStandardOutput = true; Process injectProc = Process.Start(injstartInfo); injectProc.OutputDataReceived += proc_OutputDataReceived; injectProc.BeginOutputReadLine(); //using (StreamWriter writer = new StreamWriter("important.txt", true)) //{ // writer.WriteLine("readtoend: {0}, readline: {1}", injectProc.StandardOutput.ReadToEnd(), injectProc.StandardOutput.ReadLine()); //} injectProc.WaitForExit(); //GenericGameHandler.RhCreateAndInject(path, args, 0, 0, Path.Combine(currDir, "Nucleus.Hook32.dll"), Path.Combine(currDir, "Nucleus.Hook64.dll"), IntPtr.Zero, 0, pid); //pidTest = Nucleus.Injector32.Injector32.RhCreateAndInject(path, args, 0, 0, Path.Combine(currDir, "Nucleus.Hook32.dll"), Path.Combine(currDir, "Nucleus.Hook64.dll"), IntPtr.Zero, 0, pid); } catch (Exception ex) { using (StreamWriter writer = new StreamWriter("error-log.txt", true)) { writer.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + "is64: false, ex msg: {0}, ex str: {1}", ex.Message, ex.ToString()); } } } else { using (StreamWriter writer = new StreamWriter("error-log.txt", true)) { writer.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + "Machine type: '{0}' not implemented.", GetDllMachineType(path)); } } } else // delay method { string directoryPath = Path.GetDirectoryName(path); STARTUPINFO si = new STARTUPINFO(); PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); bool success = CreateProcess(path, args, IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.CREATE_SUSPENDED, IntPtr.Zero, directoryPath, ref si, out pi); if (!success) { using (StreamWriter writer = new StreamWriter("error-log.txt", true)) { writer.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + "createprocess failed - startGamePath: {0}, startArgs: {1}, dirpath: {2}", path, args, directoryPath); } return; } ResumeThread(pi.hThread); WaitForInputIdle(pi.hProcess, uint.MaxValue); SuspendThread(pi.hThread); if (Is64Bit(path) == true) { NativeAPI.RhInjectLibrary((int)pi.dwProcessId, 0, 0, null, Path.Combine(currDir, "Nucleus.Hook64.dll"), ptr, size); pOutPID = (int)pi.dwProcessId; } else if (Is64Bit(path) == false) { try { string injectorPath = Path.Combine(currDir, "Nucleus.Inject32.exe"); ProcessStartInfo injstartInfo = new ProcessStartInfo(); injstartInfo.FileName = injectorPath; object[] injargs = new object[] { 1, (int)pi.dwProcessId, 0, 0, Path.Combine(currDir, "Nucleus.SHook32.dll"), null, isHook, renameMutex, mutexToRename, setWindow }; var sbArgs = new StringBuilder(); foreach (object arg in injargs) { sbArgs.Append(" \""); sbArgs.Append(arg); sbArgs.Append("\""); } string arguments = sbArgs.ToString(); injstartInfo.Arguments = arguments; //injstartInfo.WindowStyle = ProcessWindowStyle.Hidden; //injstartInfo.CreateNoWindow = true; injstartInfo.UseShellExecute = false; injstartInfo.RedirectStandardOutput = true; Process injectProc = Process.Start(injstartInfo); //injectProc.OutputDataReceived += proc_OutputDataReceived; //injectProc.BeginOutputReadLine(); //using (StreamWriter writer = new StreamWriter("important.txt", true)) //{ // writer.WriteLine("readtoend: {0}, readline: {1}", injectProc.StandardOutput.ReadToEnd(), injectProc.StandardOutput.ReadLine()); //} injectProc.WaitForExit(); } catch (Exception ex) { using (StreamWriter writer = new StreamWriter("error-log.txt", true)) { writer.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + "ex msg: {0}, ex str: {1}", ex.Message, ex.ToString()); } } } ResumeThread(pi.hThread); pOutPID = (int)pi.dwProcessId; } } else // regular method (no hooks) { proc = Process.Start(startInfo); pOutPID = proc.Id; } ConsoleU.WriteLine("Game started, process ID:" + pOutPID /*Marshal.ReadInt32(pid)*/ /*proc.Id*/ /*(int)pi.dwProcessId*/, Palette.Success); } #if RELEASE catch { tri++; if (tri < tries) { ConsoleU.WriteLine("Failed to start process. Retrying..."); StartGame(path, args); } } #endif }
public override CommandFeedback Execute(string[] args) { string strIP = args[1]; string audioOutput = args[2]; NAudio.CoreAudioApi.MMDeviceEnumerator enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator(); var audioDevices = enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.Active); var audioDevice = audioDevices.FirstOrDefault(c => c.FriendlyName.ToLower().Contains(audioOutput)); if (audioDevice == null) { ConsoleU.WriteLine("Failed to locate audio device", ConsoleColor.Red); return(CommandFeedback.Error); } //WasapiLoopbackCapture capture = new WasapiLoopbackCapture(); //capture.DataAvailable += (object s, WaveInEventArgs waveArgs) => { // //writer.Write(a.Buffer, 0, a.BytesRecorded); // //if (writer.Position > capture.WaveFormat.AverageBytesPerSecond * 20) { // // capture.StopRecording(); // //} //}; Device device = new Device(strIP); AsyncHelpers.RunSync(device.Connect); int lastBrightness = 1; AsyncHelpers.RunSync(() => { for (; ;) { Thread.Sleep(TimeSpan.FromMilliseconds(1001)); float peakValue = audioDevice.AudioMeterInformation.MasterPeakValue; int peakValueCent = (int)(peakValue * 120); int peakValueBars = (int)(peakValue * 120); int peakValueInt = (int)(peakValue * 200.0f); peakValueCent = MathUtil.Clamp(peakValueCent, 1, 100); //Math.Log() //device.SetBrightness((int)(audioDevice.AudioMeterInformation.MasterPeakValue * 200)); //AsyncHelpers.RunSync(() => { // return device.SetRGBColor(peakValueInt / 2, peakValueInt / 2, peakValueInt); //}); if (lastBrightness != peakValueCent) { lastBrightness = peakValueCent; AsyncHelpers.RunSync(() => { return(device.SetBrightness(peakValueCent)); }); } string strRepeat = StringUtil.RepeatCharacter('■', peakValueBars); Console.WriteLine($"({peakValueCent}) {strRepeat}"); //Console.WriteLine(peakValueInt); } }); device.Disconnect(); return(CommandFeedback.Success); }
public override CommandFeedback Execute(string[] args) { if (args.Length < 3) { return(CommandFeedback.WrongNumberOfArguments); } string target = args[1]; string pattern = args[2]; if (Directory.Exists(target)) { ConsoleU.WriteLine("Searching directory...", Palette.Wait); // target is a directory DirectoryInfo dir = new DirectoryInfo(target); FileInfo[] files = dir.GetFiles(pattern); ConsoleU.WriteLine($"Found { files.Length } files", Palette.Feedback); ConsoleU.WriteLine($"Command", Palette.Question); for (; ;) { string command = ConsoleS.ReadLine(); bool exit = false; switch (command) { case "3dsmaximport": { StringBuilder namesBuilder = new StringBuilder(); for (int i = 0; i < files.Length; i++) { string file = files[i].FullName; namesBuilder.AppendLine("ImportFile \"" + file + "\" #noPrompt"); } string str = namesBuilder.ToString(); Clipboard.SetText(namesBuilder.ToString()); ConsoleU.WriteLine($"Setting to clipboard { str } ", Palette.Feedback); } break; case "clipboard": { StringBuilder namesBuilder = new StringBuilder(); for (int i = 0; i < files.Length; i++) { string file = files[i].FullName; namesBuilder.AppendLine(file); } string str = namesBuilder.ToString(); Clipboard.SetText(str); ConsoleU.WriteLine($"Setting to clipboard { str } ", Palette.Feedback); } break; case "clipboardquotes": { StringBuilder namesBuilder = new StringBuilder(); for (int i = 0; i < files.Length; i++) { string file = files[i].FullName; namesBuilder.AppendLine('"' + file + '"'); } string str = namesBuilder.ToString(); Clipboard.SetText(str); ConsoleU.WriteLine($"Setting to clipboard { str } ", Palette.Feedback); } break; case "copy": StringCollection fileList = new StringCollection(); for (int i = 0; i < files.Length; i++) { string file = files[i].FullName; ConsoleU.WriteLine($"Setting to clipboard { file } ", Palette.Feedback); fileList.Add(file); } Clipboard.SetFileDropList(fileList); break; case "exit": exit = true; break; } if (exit) { break; } } } else { } return(CommandFeedback.Success); }
protected virtual HttpResponse RouteRequest(Stream inputStream, Stream outputStream, HttpRequest request) { List <Route> routes = this.Routes.Where(x => Regex.Match(request.Url, x.UrlRegex).Success).ToList(); Dictionary <string, string> headers = new Dictionary <string, string>(); if (request.Headers.ContainsKey("Origin")) { //headers.Add("Access-Control-Allow-Origin", request.Headers["Origin"]); } headers.Add("Connection", "keep-alive"); headers.Add("Date", DateTime.Now.ToString(CultureInfo.InvariantCulture)); headers.Add("Server", "distrolucas"); //headers.Add("Access-Control-Allow-Headers", "authorization, X-PINGOTHER, Content-Type"); //headers.Add("Access-Control-Max-Age", "86400"); //headers.Add("Keep-Alive", "timeout=2, max=100"); //headers.Add("X-DNS-Prefetch-Control", "off"); //headers.Add("X-Frame-Options", "SAMEORIGIN"); //headers.Add("Strict-Transport-Security", "max-age=15552000; includeSubDomains"); //headers.Add("X-Download-Options", "noopen"); //headers.Add("X-Content-Type-Options", "nosniff"); //headers.Add("X-XSS-Protection", "1; mode=block"); if (!routes.Any()) { // check if it's a file string pathToFile; string host = request.Headers["Host"]; string url = request.Url; int paramsIndex = url.IndexOf('?'); string urlParams = ""; if (paramsIndex != -1) { urlParams = url.Remove(0, paramsIndex); url = url.Remove(paramsIndex, url.Length - paramsIndex); } if (url.Length == 1) { pathToFile = Path.Combine(basePath, indexPath); } else { string actualPath = url.Remove(0, 1); if (actualPath.ToLower().Equals(indexPath.ToLower())) { // index page headers.Add("Location", $"http://{host}"); return(new HttpResponse() { ReasonPhrase = "OK", StatusCode = "301", ContentAsUTF8 = "", Headers = headers }); } pathToFile = Path.Combine(basePath, actualPath); } if (Directory.Exists(pathToFile)) { if (!url.EndsWith("/")) { headers.Add("Location", $"http://{host}/{request.Url.Remove(0, 1)}/"); return(new HttpResponse() { ReasonPhrase = "OK", StatusCode = "301", ContentAsUTF8 = "", Headers = headers }); } // user input a folder, check if there's an index file string pathToIndex = Path.Combine(pathToFile, indexPath); //headers.Add("Location", $"http://{host}/{request.Url.Remove(0, 1)}/index.html"); pathToFile = pathToIndex; } if (!File.Exists(pathToFile)) { pathToFile = pathToFile + ".html"; } if (File.Exists(pathToFile)) { string mime = Path.GetExtension(pathToFile).ToLower(); if (mimeTypes.ContainsKey(mime)) { headers.Add("Content-Type", mimeTypes[mime]); } else { ConsoleU.WriteLine($"UNKNOWN MIME: {mime}", ConsoleColor.Red); } HttpResponse response = new HttpResponse() { ReasonPhrase = "OK", StatusCode = "200", Headers = headers, }; response.Content = File.ReadAllBytes(pathToFile); return(response); } return(new HttpResponse() { ReasonPhrase = "NOT FOUND", StatusCode = "404", ContentAsUTF8 = "" }); //return HttpBuilder.NotFound(request.Url, headers); } //X-DNS-Prefetch-Control →off //X-Frame-Options →SAMEORIGIN //Strict-Transport-Security →max-age=15552000; includeSubDomains //X-Download-Options →noopen //X-Content-Type-Options →nosniff //X-XSS-Protection →1; mode=block //Access-Control-Allow-Origin →* //Date →Tue, 16 Jul 2019 19:09:07 GMT //Connection →keep-alive //Content-Length →0 if (request.Method == "OPTIONS") { string allRoutes = ""; for (int i = 0; i < routes.Count; i++) { string r = routes[i].Method; allRoutes += r; if (i != routes.Count - 1) { allRoutes += ", "; } } headers.Add("Access-Control-Allow-Methods", allRoutes); return(new HttpResponse() { ReasonPhrase = "", StatusCode = "204", Headers = headers }); } Route route = routes.SingleOrDefault(x => x.Method == request.Method); if (route == null) { Console.WriteLine("Method Not Allowed"); return(new HttpResponse() { ReasonPhrase = "Method Not Allowed", StatusCode = "405", }); } // extract the path if there is one var match = Regex.Match(request.Url, route.UrlRegex); if (match.Groups.Count > 1) { request.Path = match.Groups[1].Value; } else { request.Path = request.Url; } // trigger the route handler... request.Route = route; try { HttpResponse response = route.Callable(request); if (response.Headers == null) { response.Headers = headers; } else { foreach (var header in headers) { if (!response.Headers.ContainsKey(header.Key)) { response.Headers.Add(header.Key, header.Value); } } } return(response); } catch (Exception) { //log.Error(ex); return(HttpBuilder.InternalServerError(headers)); } }
static void Main(string[] args) { // We need this, else Windows will fake // all the data about monitors inside the application User32Util.SetProcessDpiAwareness(ProcessDPIAwareness.ProcessPerMonitorDPIAware); if (args.Length == 0) { ConsoleU.WriteLine("Invalid usage! Need arguments to proceed!", Palette.Error); return; } #if RELEASE try #endif { string base64 = Encoding.UTF8.GetString(Convert.FromBase64String(args[0])); StartGameData data = JsonConvert.DeserializeObject <StartGameData>(base64); switch (data.Task) { case GameStarterTask.StartGame: { string gamePath = data.Parameters[0]; string gameArgs = data.Parameters[1]; string gameWorkingDir = data.Parameters[2]; ConsoleU.WriteLine($"Start game: EXE: {gamePath} ARGS: {gameArgs} WORKDIR: {gameWorkingDir}", Palette.Feedback); StartGame(gamePath, gameArgs, gameWorkingDir); } break; case GameStarterTask.KillMutex: { string procId = data.Parameters[0]; ConsoleU.WriteLine($"Process ID {procId} request to kill mutexes", Palette.Wait); proc = Process.GetProcessById(int.Parse(procId)); ConsoleU.WriteLine($"Trying to kill mutexes {data.Parameters.Length - 1} mutexes", Palette.Wait); for (int j = 1; j < data.Parameters.Length; j++) { string m = data.Parameters[j]; string prefix = $"({j}/{data.Parameters.Length - 1}) "; ConsoleU.WriteLine(prefix + "Trying to kill mutex: " + m, Palette.Feedback); if (!ProcessUtil.KillMutex(proc, m)) { ConsoleU.WriteLine(prefix + "Mutex " + m + " could not be killed", Palette.Error); } else { ConsoleU.WriteLine(prefix + "Mutex killed " + m, Palette.Success); } Thread.Sleep(150); } } break; case GameStarterTask.QueryMutex: { string procId = data.Parameters[0]; ConsoleU.WriteLine($"Process ID {procId} request to be queried for mutexes", Palette.Wait); proc = Process.GetProcessById(int.Parse(procId)); ConsoleU.WriteLine($"Trying to query for any mutex's existance", Palette.Wait); for (int j = 0; j < data.Parameters.Length; j++) { string m = data.Parameters[j]; string prefix = $"({j + 1}/{data.Parameters.Length}) "; ConsoleU.WriteLine(prefix + "Trying to kill mutex: " + m, Palette.Feedback); if (!ProcessUtil.KillMutex(proc, m)) { ConsoleU.WriteLine(prefix + "Mutex " + m + " could not be killed", Palette.Error); } else { ConsoleU.WriteLine(prefix + "Mutex killed " + m, Palette.Success); } Thread.Sleep(150); } } break; case GameStarterTask.FindProcessId: { string procId = data.Parameters[0]; int id = int.Parse(procId); try { proc = Process.GetProcessById(id); ConsoleU.WriteLine($"Process ID {id} found!", Palette.Success); } catch { ConsoleU.WriteLine($"Process ID {id} not found", Palette.Error); } } break; case GameStarterTask.ListMonitors: break; } } #if RELEASE catch (Exception ex) { ConsoleU.WriteLine(ex.Message); } #endif }
public override CommandFeedback Execute(string[] args) { string strSourceFolder = args[2]; string strBundleName = args[1]; sourceFiles = new List <FileInfo>(); ScanFolder(new DirectoryInfo(strSourceFolder), new List <string>() { "*.meta" }, sourceFiles); int noBundle = 0; int hasBundle = 0; int noVariant = 0; int doesntExist = 0; for (int i = 0; i < sourceFiles.Count; i++) { FileInfo file = sourceFiles[i]; string strFullName = file.FullName; // check if meta is for folder string strNoMeta = strFullName.Remove(strFullName.Length - 5, 5); if (!File.Exists(strNoMeta)) { ConsoleU.WriteLine($"File doesnt exist: " + strNoMeta, ConsoleColor.Red); doesntExist++; continue; } string strFileText; using (Stream str = file.OpenRead()) { StreamReader strReader = new StreamReader(str); strFileText = strReader.ReadToEnd(); } const string STR_BUNDLE = "assetBundleName"; int numBundleIndex = strFileText.IndexOf(STR_BUNDLE); if (numBundleIndex != -1) { // get word after bundle int numVariantIndex = strFileText.IndexOf("assetBundleVariant"); if (numVariantIndex == -1) { ConsoleU.WriteLine($"Asset has bundle but no variant: " + file.FullName, ConsoleColor.Red); noVariant++; continue; } string bundleName = strFileText.Substring(numBundleIndex, numVariantIndex - numBundleIndex); if (bundleName.IndexOf(strBundleName) != -1) { ConsoleU.WriteLine($"Asset has bundle: " + file.FullName, ConsoleColor.Yellow); hasBundle++; continue; } strFileText = strFileText.Insert(numBundleIndex + STR_BUNDLE.Length + 2, strBundleName); } else { strFileText = strFileText + $"\r\n assetBundleName: {strBundleName}\r\n assetBundleVariant: "; } ConsoleU.WriteLine($"Asset has no bundle: " + file.FullName, ConsoleColor.Green); noBundle++; //continue; file.Delete(); File.WriteAllText(strFullName, strFileText); } ConsoleU.WriteLine($"Total: {hasBundle}/{noBundle}", ConsoleColor.Green); ConsoleU.WriteLine($"Total: No variant: {noVariant} Doesnt Exist: {doesntExist}", ConsoleColor.Green); return(CommandFeedback.Success); }
private static void ExecuteTask(StartGameData data) { switch (data.Task) { case GameStarterTask.StartGame: { string gamePath = data.Parameters[0]; string gameArgs = data.Parameters[1]; string gameWorkingDir = data.Parameters[2]; ConsoleU.WriteLine($"Start game: EXE: {gamePath} ARGS: {gameArgs} WORKDIR: {gameWorkingDir}", Palette.Feedback); StartGame(gamePath, gameArgs, gameWorkingDir); } break; case GameStarterTask.KillMutex: { Log.WriteLine($"Kill Mutex Task"); string procId = data.Parameters[0]; string[] mutexes = new string[data.Parameters.Length - 1]; for (int j = 1; j < data.Parameters.Length; j++) { string m = data.Parameters[j]; mutexes[j - 1] = m; } KillMutex(procId, mutexes); WriteToDataFile(Assembly.GetEntryAssembly().Location, true.ToString()); } break; case GameStarterTask.RenameMutex: { Log.WriteLine($"Rename Mutex Task"); string procId = data.Parameters[0]; string[] mutexes = new string[data.Parameters.Length - 1]; for (int j = 1; j < data.Parameters.Length; j++) { string m = data.Parameters[j]; mutexes[j - 1] = m; } KillMutex(procId, mutexes); WriteToDataFile(Assembly.GetEntryAssembly().Location, true.ToString()); } break; case GameStarterTask.ScanKillMutex: { Log.WriteLine($"Scan Kill Mutex"); List <int> processIds = new List <int>(); for (int j = 0; j < data.Parameters.Length; j++) { string scanMutexDataRaw = data.Parameters[j]; ScanMutexData scanMutex = JsonConvert.DeserializeObject <ScanMutexData>(scanMutexDataRaw); Log.WriteLine($"Kill Mutex for process {scanMutex.ProcessName}"); for (; ;) { Process[] procs = Process.GetProcessesByName(scanMutex.ProcessName); if (procs == null || procs.Length == 0) { Thread.Sleep(250); } else { // kill mutexes bool killedMutexes = false; for (int k = 0; k < procs.Length; k++) { Process p = procs[k]; if (processIds.Contains(p.Id)) { continue; } // start other process, as the mutexes are only truly killed // when the process is ended if (scanMutex.ShouldRename) { StartGameUtil.RenameMutex(p, scanMutex.Mutexes); } else { StartGameUtil.KillMutex(p, scanMutex.Mutexes); } //KillMutex(p.Id.ToString(), scanMutex.Mutexes); processIds.Add(p.Id); killedMutexes = true; break; } if (killedMutexes) { Log.WriteLine($"Killed all mutexes for process {scanMutex.ProcessName}"); WriteToDataFile(Assembly.GetEntryAssembly().Location, true.ToString()); break; } } } } } break; case GameStarterTask.MultipleTasks: { Log.WriteLine($"Multiple tasks"); for (int j = 0; j < data.Parameters.Length; j++) { string taskDataRaw = data.Parameters[j]; StartGameData taskData = JsonConvert.DeserializeObject <StartGameData>(taskDataRaw); Log.WriteLine($"Executing task {j + 1}"); ExecuteTask(taskData); } } break; case GameStarterTask.QueryMutex: { string procId = data.Parameters[0]; string[] mutexes = new string[data.Parameters.Length - 1]; for (int j = 1; j < data.Parameters.Length; j++) { string m = data.Parameters[j]; mutexes[j - 1] = m; } } break; case GameStarterTask.ListMonitors: break; case GameStarterTask.ScanGames: { // initialize game manager to read available handlers GameManager gameManager = new GameManager(); List <string> games = new List <string>(); for (int j = 0; j < data.Parameters.Length; j++) { string driveName = data.Parameters[j]; //SearchStorageInfo info = JsonConvert.DeserializeObject<SearchStorageInfo>(storageData); DriveInfo drive = new DriveInfo(driveName); if (!drive.IsReady) { continue; } Log.WriteLine($"> Searching drive {drive.Name} for game executables"); Dictionary <ulong, FileNameAndParentFrn> allExes = new Dictionary <ulong, FileNameAndParentFrn>(); MFTReader mft = new MFTReader(); mft.Drive = drive.RootDirectory.FullName; // TODO: search only for specific games? mft.EnumerateVolume(out allExes, new string[] { ".exe" }); foreach (KeyValuePair <UInt64, FileNameAndParentFrn> entry in allExes) { FileNameAndParentFrn file = (FileNameAndParentFrn)entry.Value; string name = file.Name; string lower = name.ToLower(); string path = mft.GetFullPath(file); if (path.Contains("$Recycle.Bin") || path.Contains(@"\Instance")) { // noope continue; } if (GameManager.Instance.AnyGame(lower)) { Log.WriteLine($"Found game at path: {path}"); games.Add(path); } } } WriteToDataFile(Assembly.GetEntryAssembly().Location, JsonConvert.SerializeObject(games)); } break; case GameStarterTask.SymlinkFolders: for (int j = 0; j < data.Parameters.Length; j++) { string symData = data.Parameters[j]; Log.WriteLine($"Symlink game instance {j + 1}"); SymlinkGameData gameData = JsonConvert.DeserializeObject <SymlinkGameData>(symData); int exitCode; WinDirectoryUtil.LinkDirectory(gameData.SourcePath, new DirectoryInfo(gameData.SourcePath), gameData.DestinationPath, out exitCode, gameData.DirExclusions, gameData.FileExclusions, gameData.FileCopies, true); } WriteToDataFile(Assembly.GetEntryAssembly().Location, true.ToString()); break; } }
static void Main(string[] args) { // We need this, else Windows will fake // all the data about monitors inside the application User32Util.SetProcessDpiAwareness(ProcessDPIAwareness.ProcessPerMonitorDPIAware); if (args.Length == 0) { ConsoleU.WriteLine("Invalid usage! Need arguments to proceed!", Palette.Error); return; } #if RELEASE try #endif { for (int i = 0; i < args.Length; i++) { string arg = args[i]; ConsoleU.WriteLine("Parsing line " + i + ": " + arg, Palette.Feedback); string argument = ""; for (int j = i; j < args.Length; j++) { string skey = args[j]; if (!skey.Contains("monitors") && !skey.Contains("game") && !skey.Contains("mutex") && !skey.Contains("proc") && !skey.Contains("output")) { i++; if (string.IsNullOrEmpty(argument)) { argument = skey; } else { argument = argument + " " + skey; } } } ConsoleU.WriteLine("Extra arguments:" + argument, Palette.Feedback); string[] splited = (arg + argument).Split(':'); string key = splited[0].ToLower(); if (key.Contains("monitors")) { } else if (key.Contains("game")) { string data = splited[1]; string[] subArgs = data.Split(';'); string path = subArgs[0]; string argu = null; if (subArgs.Length > 1) { argu = subArgs[1]; } string workingDir = null; if (path.Contains("|")) { string[] div = path.Split('|'); path = div[0]; workingDir = div[1]; } ConsoleU.WriteLine($"Start game: EXE: {path} ARGS: {argu} WORKDIR: {workingDir}", Palette.Feedback); StartGame(path, argu, workingDir); } else if (key.Contains("mutex")) { string[] mutex = splited[1].Split(';'); ConsoleU.WriteLine("Trying to kill mutexes", Palette.Wait); for (int j = 0; j < mutex.Length; j++) { string m = mutex[j]; ConsoleU.WriteLine("Trying to kill mutex: " + m, Palette.Feedback); if (!ProcessUtil.KillMutex(proc, m)) { ConsoleU.WriteLine("Mutex " + m + " could not be killed", Palette.Error); } else { ConsoleU.WriteLine("Mutex killed " + m, Palette.Success); } Thread.Sleep(150); } } else if (key.Contains("proc")) { string procId = splited[1]; int id = int.Parse(procId); try { proc = Process.GetProcessById(id); ConsoleU.WriteLine($"Process ID {id} found!", Palette.Success); } catch { ConsoleU.WriteLine($"Process ID {id} not found", Palette.Error); } } else if (key.Contains("output")) { string[] mutex = splited[1].Split(';'); bool all = true; for (int j = 0; j < mutex.Length; j++) { string m = mutex[j]; ConsoleU.WriteLine("Requested mutex: " + m, Palette.Error); bool exists = ProcessUtil.MutexExists(proc, m); if (!exists) { all = false; } Thread.Sleep(500); } Console.WriteLine(all.ToString()); } } } #if RELEASE catch (Exception ex) { ConsoleU.WriteLine(ex.Message); } #endif }
static void Main(string[] args) { // We need this, else Windows will fake // all the data about monitors inside the application User32Util.SetProcessDpiAwareness(ProcessDPIAwareness.ProcessPerMonitorDPIAware); if (args.Length == 0) { ConsoleU.WriteLine("Invalid usage! Need arguments to proceed!", Palette.Error); return; } #if RELEASE try #endif { for (int i = 0; i < args.Length; i++) { string arg = args[i]; ConsoleU.WriteLine("Parsing line " + i + ": " + arg, Palette.Feedback); //Log(string.Format("Parsing line {0}: {1}", i, arg)); string argument = ""; for (int j = i; j < args.Length; j++) { string skey = args[j]; if (!skey.Contains("monitors") && !skey.Contains("game") && !skey.Contains("partialmutex") && !skey.Contains("mutextype") && !skey.Contains("mutex") && !skey.Contains("proc") && !skey.Contains("hook") && !skey.Contains("delay") && !skey.Contains("renamemutex") && !skey.Contains("mutextorename") && !skey.Contains("setwindow") && !skey.Contains("isdebug") && !skey.Contains("nucleusfolderpath") && !skey.Contains("blockraw") //&& !skey.Contains("rawhid") && !skey.Contains("output")) { i++; if (string.IsNullOrEmpty(argument)) { argument = skey; } else { argument = argument + " " + skey; } } } //Log("Extra arguments:" + argument); ConsoleU.WriteLine("Extra arguments:" + argument, Palette.Feedback); string[] splited = (arg + argument).Split(new string[] { "|::|" }, StringSplitOptions.None); string key = splited[0].ToLower(); if (key.Contains("monitors")) { } else if (key.Contains("hook")) { isHook = Boolean.Parse(splited[1]); } else if (key.Contains("delay")) { isDelay = Boolean.Parse(splited[1]); } else if (key.Contains("renamemutex")) { renameMutex = Boolean.Parse(splited[1]); } else if (key.Contains("mutextorename")) { mutexToRename = splited[1]; } else if (key.Contains("partialmutex")) { partialMutex = Boolean.Parse(splited[1]); } else if (key.Contains("setwindow")) { setWindow = Boolean.Parse(splited[1]); } else if (key.Contains("isdebug")) { isDebug = Boolean.Parse(splited[1]); } else if (key.Contains("nucleusfolderpath")) { nucleusFolderPath = splited[1]; } else if (key.Contains("blockraw")) { blockRaw = Boolean.Parse(splited[1]); } //else if (key.Contains("rawhid")) //{ // rawHid = splited[1]; //} else if (key.Contains("game")) { string data = splited[1]; string[] subArgs = data.Split(';'); string path = subArgs[0]; string argu = null; if (subArgs.Length > 1) { argu = subArgs[1]; } string workingDir = null; if (path.Contains("|")) { string[] div = path.Split('|'); path = div[0]; workingDir = div[1]; } Log($"EXE: {path} ARGS: {argu} WORKDIR: {workingDir}"); ConsoleU.WriteLine($"Start game: EXE: {path} ARGS: {argu} WORKDIR: {workingDir}", Palette.Feedback); StartGame(path, argu, workingDir); } else if (key.Contains("mutextype")) { mt = splited[1]; } else if (key.Contains("mutex")) { string[] mutex = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None); ConsoleU.WriteLine("Trying to kill mutexes", Palette.Wait); for (int j = 0; j < mutex.Length; j++) { string m = mutex[j]; ConsoleU.WriteLine("Trying to kill mutex: " + m, Palette.Feedback); if (!ProcessUtil.KillMutex(proc, mt, m, partialMutex)) { ConsoleU.WriteLine("Mutex " + m + " could not be killed", Palette.Error); } else { ConsoleU.WriteLine("Mutex killed " + m, Palette.Success); } Thread.Sleep(150); } } else if (key.Contains("proc")) { string procId = splited[1]; int id = int.Parse(procId); try { proc = Process.GetProcessById(id); ConsoleU.WriteLine($"Process ID {id} found!", Palette.Success); } catch { ConsoleU.WriteLine($"Process ID {id} not found", Palette.Error); } } else if (key.Contains("output")) { string[] mutex = splited[1].Split(';'); bool all = true; for (int j = 0; j < mutex.Length; j++) { string m = mutex[j]; ConsoleU.WriteLine("Requested mutex: " + m, Palette.Error); bool exists = ProcessUtil.MutexExists(proc, mt, m, partialMutex); if (!exists) { all = false; } Thread.Sleep(500); } Console.WriteLine(all.ToString()); } } } #if RELEASE catch (Exception ex) { ConsoleU.WriteLine(ex.Message); } #endif }