public void ExtractFile_2() { // Type 2 EngineState s = EngineTests.CreateEngineState(); string pPath = Path.Combine("%TestBench%", "EncodedFile", "ExtractFileTests.script"); pPath = StringEscaper.Preprocess(s, pPath); Plugin p = s.Project.LoadPluginMonkeyPatch(pPath); byte[] extractDigest; using (MemoryStream ms = EncodedFile.ExtractFile(p, "FolderExample", "Type2.7z")) { extractDigest = HashHelper.CalcHash(HashType.SHA256, ms); } string originFile = Path.Combine("%TestBench%", "EncodedFile", "Type2.7z"); originFile = StringEscaper.Preprocess(s, originFile); byte[] originDigest; using (FileStream fs = new FileStream(originFile, FileMode.Open)) { originDigest = HashHelper.CalcHash(HashType.SHA256, fs); } // Compare Hash Assert.IsTrue(originDigest.SequenceEqual(extractDigest)); }
public void ExtractFile() { void Template(string fileName) { // Type 1 EngineState s = EngineTests.CreateEngineState(); string srcScript = Path.Combine("%TestBench%", "EncodedFile", "ExtractFileTests.script"); srcScript = StringEscaper.Preprocess(s, srcScript); Script sc = s.Project.LoadScriptRuntime(srcScript, new LoadScriptRuntimeOptions()); byte[] extractDigest; using (MemoryStream ms = new MemoryStream()) { EncodedFile.ExtractFile(sc, "FolderExample", fileName, ms, null); ms.Position = 0; extractDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, ms); } string originFile = Path.Combine("%TestBench%", "EncodedFile", fileName); originFile = StringEscaper.Preprocess(s, originFile); byte[] originDigest; using (FileStream fs = new FileStream(originFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { originDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, fs); } // Compare Hash Assert.IsTrue(originDigest.SequenceEqual(extractDigest)); } Template("Type1.jpg"); // Type 1 Template("Type2.7z"); // Type 2 Template("Type3.pdf"); // Type 3 }
public static List <LogInfo> ExtractAllFiles(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_ExtractAllFiles)); CodeInfo_ExtractAllFiles info = cmd.Info as CodeInfo_ExtractAllFiles; string pluginFile = StringEscaper.Preprocess(s, info.PluginFile); string dirName = StringEscaper.Preprocess(s, info.DirName); string destDir = StringEscaper.Preprocess(s, info.DestDir); Plugin p = Engine.GetPluginInstance(s, cmd, s.CurrentPlugin.FullPath, pluginFile, out bool inCurrentPlugin); if (StringEscaper.PathSecurityCheck(destDir, out string errorMsg) == false) { logs.Add(new LogInfo(LogState.Error, errorMsg)); return(logs); } List <string> dirs = p.Sections["EncodedFolders"].Lines; bool dirNameValid = dirs.Any(d => d.Equals(dirName, StringComparison.OrdinalIgnoreCase)); if (dirNameValid == false) { throw new ExecuteException($"Directory [{dirName}] not exists in [{pluginFile}]"); } if (!Directory.Exists(destDir)) { if (File.Exists(destDir)) { logs.Add(new LogInfo(LogState.Error, $"File [{destDir}] is not a directory")); return(logs); } else { logs.Add(new LogInfo(LogState.Error, $"Directory [{destDir}] does not exist")); return(logs); } } List <string> lines = p.Sections[dirName].Lines; Dictionary <string, string> fileDict = Ini.ParseIniLinesIniStyle(lines); foreach (string file in fileDict.Keys) { using (MemoryStream ms = EncodedFile.ExtractFile(p, dirName, file)) using (FileStream fs = new FileStream(Path.Combine(destDir, file), FileMode.Create, FileAccess.Write)) { ms.Position = 0; ms.CopyTo(fs); } } logs.Add(new LogInfo(LogState.Success, $"Encoded folder [{dirName}] extracted to [{destDir}]")); return(logs); }
public void AttachFile_Template(string fileName) { EngineState s = EngineTests.CreateEngineState(); string dirPath = StringEscaper.Preprocess(s, Path.Combine("%TestBench%", "EncodedFile")); string blankPath = Path.Combine(dirPath, "EncodeFileTests_Blank.script"); string pPath = Path.Combine(dirPath, "EncodeFileTests.script"); File.Copy(blankPath, pPath, true); Plugin p = s.Project.LoadPluginMonkeyPatch(pPath); string originFile = Path.Combine(dirPath, fileName); p = EncodedFile.AttachFile(p, "FolderExample", fileName, originFile, EncodedFile.EncodeMode.Compress); try { // Check whether file was successfully encoded Assert.IsTrue(p.Sections.ContainsKey("EncodedFolders")); List <string> folders = p.Sections["EncodedFolders"].GetLines(); folders = folders.Where(x => x.Equals(string.Empty, StringComparison.Ordinal) == false).ToList(); Assert.IsTrue(folders.Count == 1); Assert.IsTrue(folders[0].Equals("FolderExample", StringComparison.Ordinal)); Assert.IsTrue(p.Sections.ContainsKey("FolderExample")); List <string> fileInfos = p.Sections["FolderExample"].GetLinesOnce(); fileInfos = fileInfos.Where(x => x.Equals(string.Empty, StringComparison.Ordinal) == false).ToList(); Assert.IsTrue(fileInfos[0].StartsWith($"{fileName}=", StringComparison.Ordinal)); Assert.IsTrue(p.Sections.ContainsKey($"EncodedFile-FolderExample-{fileName}")); List <string> encodedFile = p.Sections[$"EncodedFile-FolderExample-{fileName}"].GetLinesOnce(); encodedFile = encodedFile.Where(x => x.Equals(string.Empty, StringComparison.Ordinal) == false).ToList(); Assert.IsTrue(1 < encodedFile.Count); Assert.IsTrue(encodedFile[0].StartsWith("lines=", StringComparison.Ordinal)); // Check whether file can be successfully extracted byte[] extractDigest; using (MemoryStream ms = EncodedFile.ExtractFile(p, "FolderExample", fileName)) { extractDigest = HashHelper.CalcHash(HashType.SHA256, ms); } byte[] originDigest; using (FileStream fs = new FileStream(originFile, FileMode.Open)) { originDigest = HashHelper.CalcHash(HashType.SHA256, fs); } Assert.IsTrue(originDigest.SequenceEqual(extractDigest)); } finally { File.Delete(pPath); } }
/* * WB082 Behavior * ExtractFile : DestDir must be Directory, create if not exists. * Ex) (...),README.txt,%BaseDir%\Temp\Hello * -> No Hello : Create direcotry "Hello" and extract files into new directory. * -> Hello is a file : Failure * -> Hello is a directory : Extract files into directory. * * ExtractAllFiles * Ex) (...),Fonts,%BaseDir%\Temp\Hello * -> No Hello : Failure * -> Hello is a file : Failure * -> Hello is a direcotry : Extract files into directory. * */ public static List <LogInfo> ExtractFile(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_ExtractFile)); CodeInfo_ExtractFile info = cmd.Info as CodeInfo_ExtractFile; string pluginFile = StringEscaper.Preprocess(s, info.PluginFile); string dirName = StringEscaper.Preprocess(s, info.DirName); string fileName = StringEscaper.Preprocess(s, info.FileName); string destDir = StringEscaper.Preprocess(s, info.DestDir); // Should be directory name Plugin p = Engine.GetPluginInstance(s, cmd, s.CurrentPlugin.FullPath, pluginFile, out bool inCurrentPlugin); if (StringEscaper.PathSecurityCheck(destDir, out string errorMsg) == false) { logs.Add(new LogInfo(LogState.Error, errorMsg)); return(logs); } if (!Directory.Exists(destDir)) // DestDir already exists { if (File.Exists(destDir)) // Error, cannot proceed { logs.Add(new LogInfo(LogState.Error, $"File [{destDir}] is not a directory.")); return(logs); } else { Directory.CreateDirectory(destDir); } } string destPath = Path.Combine(destDir, fileName); using (MemoryStream ms = EncodedFile.ExtractFile(p, dirName, fileName)) using (FileStream fs = new FileStream(destPath, FileMode.Create, FileAccess.Write)) { ms.Position = 0; ms.CopyTo(fs); } logs.Add(new LogInfo(LogState.Success, $"Encoded file [{fileName}] extracted to [{destDir}]")); return(logs); }
public static List <LogInfo> ExtractAndRun(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_ExtractAndRun)); CodeInfo_ExtractAndRun info = cmd.Info as CodeInfo_ExtractAndRun; string pluginFile = StringEscaper.Preprocess(s, info.PluginFile); string dirName = StringEscaper.Preprocess(s, info.DirName); string fileName = StringEscaper.Preprocess(s, info.FileName); List <string> parameters = StringEscaper.Preprocess(s, info.Params); Plugin p = Engine.GetPluginInstance(s, cmd, s.CurrentPlugin.FullPath, pluginFile, out bool inCurrentPlugin); string destPath = Path.GetTempFileName(); if (StringEscaper.PathSecurityCheck(destPath, out string errorMsg) == false) { logs.Add(new LogInfo(LogState.Error, errorMsg)); return(logs); } using (MemoryStream ms = EncodedFile.ExtractFile(p, dirName, info.FileName)) using (FileStream fs = new FileStream(destPath, FileMode.Create, FileAccess.Write)) { ms.Position = 0; ms.CopyTo(fs); } Process proc = new Process(); proc.StartInfo.FileName = destPath; proc.StartInfo.UseShellExecute = true; proc.StartInfo.Verb = "Open"; proc.Start(); logs.Add(new LogInfo(LogState.Success, $"Encoded file [{fileName}] extracted and executed")); return(logs); }
/* * WB082 Behavior * ExtractFile : DestDir must be Directory, create if not exists. * Ex) (...),README.txt,%BaseDir%\Temp\Hello * -> No Hello : Create directory "Hello" and extract files into new directory. * -> Hello is a file : Failure * -> Hello is a directory : Extract files into directory. * * ExtractAllFiles * Ex) (...),Fonts,%BaseDir%\Temp\Hello * -> No Hello : Failure * -> Hello is a file : Failure * -> Hello is a directory : Extract files into directory. * * PEBakery Behavior * ExtractFile/ExtractAllFiles : DestDir must be Directory, create if not exists. * Ex) (...),README.txt,%BaseDir%\Temp\Hello * -> No Hello : Create directory "Hello" and extract files into new directory. * -> Hello is a file : Failure * -> Hello is a directory : Extract files into directory. */ public static List <LogInfo> ExtractFile(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_ExtractFile info = cmd.Info.Cast <CodeInfo_ExtractFile>(); string scriptFile = StringEscaper.Preprocess(s, info.ScriptFile); string dirName = StringEscaper.Preprocess(s, info.DirName); string fileName = StringEscaper.Preprocess(s, info.FileName); string destDir = StringEscaper.Preprocess(s, info.DestDir); // Should be directory name Script sc = Engine.GetScriptInstance(s, s.CurrentScript.RealPath, scriptFile, out _); // Check if encoded file exist if (!EncodedFile.ContainsFile(sc, dirName, fileName)) { return(LogInfo.LogErrorMessage(logs, $"Encoded file [{dirName}\\{fileName}] not found in script [{sc.RealPath}].")); } // Filter dest path if (!StringEscaper.PathSecurityCheck(destDir, out string errorMsg)) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } if (!Directory.Exists(destDir)) // DestDir already exists { if (File.Exists(destDir)) // Error, cannot proceed { return(LogInfo.LogErrorMessage(logs, $"File [{destDir}] is not a directory.")); } Directory.CreateDirectory(destDir); } s.MainViewModel.SetBuildCommandProgress("ExtractFile Progress", 1); try { object progressLock = new object(); IProgress <double> progress = new Progress <double>(x => { lock (progressLock) { s.MainViewModel.BuildCommandProgressValue = x; if (x < EncodedFile.Base64ReportFactor) { // [Stage 1] Base64 s.MainViewModel.BuildCommandProgressText = $"Reading \"{fileName}\" from script\r\n({x * 100:0.0}%)"; } else { // [Stage 2] Decompress s.MainViewModel.BuildCommandProgressText = $"Decompressing \"{fileName}\"\r\n({x * 100:0.0}%)"; } } }); string destPath = Path.Combine(destDir, fileName); using (FileStream fs = new FileStream(destPath, FileMode.Create, FileAccess.Write)) { EncodedFile.ExtractFile(sc, dirName, fileName, fs, progress); } } finally { s.MainViewModel.ResetBuildCommandProgress(); } logs.Add(new LogInfo(LogState.Success, $"Encoded file [{fileName}] was extracted to [{destDir}]")); return(logs); }
public static List <LogInfo> ExtractAllFiles(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_ExtractAllFiles info = cmd.Info.Cast <CodeInfo_ExtractAllFiles>(); string scriptFile = StringEscaper.Preprocess(s, info.ScriptFile); string dirName = StringEscaper.Preprocess(s, info.DirName); string destDir = StringEscaper.Preprocess(s, info.DestDir); Script sc = Engine.GetScriptInstance(s, s.CurrentScript.RealPath, scriptFile, out _); // Check if encoded file exist if (!EncodedFile.ContainsFolder(sc, dirName)) { return(LogInfo.LogErrorMessage(logs, $"Encoded folder [{dirName}] not found in script [{sc.RealPath}].")); } // Filter dest path if (!StringEscaper.PathSecurityCheck(destDir, out string errorMsg)) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } string[] dirs = sc.Sections[ScriptSection.Names.EncodedFolders].Lines; if (!dirs.Any(d => d.Equals(dirName, StringComparison.OrdinalIgnoreCase))) { return(LogInfo.LogErrorMessage(logs, $"Directory [{dirName}] not exists in [{scriptFile}]")); } if (!Directory.Exists(destDir)) { if (File.Exists(destDir)) { return(LogInfo.LogErrorMessage(logs, $"File [{destDir}] is not a directory")); } Directory.CreateDirectory(destDir); } string[] lines = sc.Sections[dirName].Lines; Dictionary <string, string> fileDict = IniReadWriter.ParseIniLinesIniStyle(lines); int fileCount = fileDict.Count; s.MainViewModel.SetBuildCommandProgress("ExtractAndRun Progress", fileCount); try { int i = 0; foreach (string file in fileDict.Keys) { object progressLock = new object(); IProgress <double> progress = new Progress <double>(x => { lock (progressLock) { s.MainViewModel.BuildCommandProgressText = $"Decompressing \"{file}\"\r\n({(x + i) * 100 / fileCount:0.0}%)"; s.MainViewModel.BuildCommandProgressValue = x + i; } }); using (FileStream fs = new FileStream(Path.Combine(destDir, file), FileMode.Create, FileAccess.Write)) { EncodedFile.ExtractFile(sc, dirName, file, fs, progress); } i += 1; } } finally { s.MainViewModel.ResetBuildCommandProgress(); } logs.Add(new LogInfo(LogState.Success, $"Encoded folder [{dirName}] was extracted to [{destDir}]")); return(logs); }
public static List <LogInfo> ExtractAndRun(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_ExtractAndRun info = cmd.Info.Cast <CodeInfo_ExtractAndRun>(); string scriptFile = StringEscaper.Preprocess(s, info.ScriptFile); string dirName = StringEscaper.Preprocess(s, info.DirName); string fileName = StringEscaper.Preprocess(s, info.FileName); Script sc = Engine.GetScriptInstance(s, s.CurrentScript.RealPath, scriptFile, out _); // Check if encoded file exist if (!EncodedFile.ContainsFile(sc, dirName, fileName)) { return(LogInfo.LogErrorMessage(logs, $"Encoded file [{dirName}\\{fileName}] not found in script [{sc.RealPath}].")); } string tempDir = FileHelper.GetTempDir(); string tempPath = Path.Combine(tempDir, fileName); s.MainViewModel.SetBuildCommandProgress("ExtractAndRun Progress", 1); try { object progressLock = new object(); IProgress <double> progress = new Progress <double>(x => { lock (progressLock) { s.MainViewModel.BuildCommandProgressValue = x; if (x < EncodedFile.Base64ReportFactor) { // [Stage 1] Base64 s.MainViewModel.BuildCommandProgressText = $"Reading \"{fileName}\" from script\r\n({x * 100:0.0}%)"; } else { // [Stage 2] Decompress s.MainViewModel.BuildCommandProgressText = $"Decompressing \"{fileName}\"\r\n({x * 100:0.0}%)"; } } }); using (FileStream fs = new FileStream(tempPath, FileMode.Create, FileAccess.Write)) { EncodedFile.ExtractFile(sc, dirName, info.FileName, fs, progress); } } finally { s.MainViewModel.ResetBuildCommandProgress(); } string _params = null; using (Process proc = new Process()) { proc.EnableRaisingEvents = true; proc.StartInfo = new ProcessStartInfo { FileName = tempPath, UseShellExecute = true, }; if (!string.IsNullOrEmpty(info.Params)) { _params = StringEscaper.Preprocess(s, info.Params); proc.StartInfo.Arguments = _params; } proc.Exited += (object sender, EventArgs e) => { if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } // ReSharper disable once AccessToDisposedClosure proc.Dispose(); }; proc.Start(); } if (_params == null) { logs.Add(new LogInfo(LogState.Success, $"Extracted and executed [{fileName}]")); } else { logs.Add(new LogInfo(LogState.Success, $"Extracted and executed [{fileName} {_params}]")); } return(logs); }
public void AttachFile() { void Template(string fileName, EncodedFile.EncodeMode encodeMode) { EngineState s = EngineTests.CreateEngineState(); string srcDir = StringEscaper.Preprocess(s, Path.Combine("%TestBench%", "EncodedFile")); string srcScript = Path.Combine(srcDir, "Blank.script"); string destDir = FileHelper.GetTempDir(); string destScript = Path.Combine(destDir, "EncodeFileTests.script"); File.Copy(srcScript, destScript, true); try { Script sc = s.Project.LoadScriptRuntime(destScript, new LoadScriptRuntimeOptions()); string originFile = Path.Combine(srcDir, fileName); EncodedFile.AttachFile(sc, "FolderExample", fileName, originFile, encodeMode, null); // Check whether file was successfully encoded Assert.IsTrue(sc.Sections.ContainsKey("EncodedFolders")); string[] folders = sc.Sections["EncodedFolders"].Lines .Where(x => x.Length != 0) .ToArray(); Assert.IsTrue(folders.Length == 2); Assert.IsTrue(folders[0].Equals("FolderExample", StringComparison.Ordinal)); Assert.IsTrue(sc.Sections.ContainsKey("FolderExample")); string[] fileInfos = sc.Sections["FolderExample"].Lines .Where(x => x.Length != 0) .ToArray(); Assert.IsTrue(fileInfos[0].StartsWith($"{fileName}=", StringComparison.Ordinal)); Assert.IsTrue(sc.Sections.ContainsKey($"EncodedFile-FolderExample-{fileName}")); string[] encodedFile = sc.Sections[$"EncodedFile-FolderExample-{fileName}"].Lines .Where(x => x.Length != 0) .ToArray(); Assert.IsTrue(1 < encodedFile.Length); Assert.IsTrue(encodedFile[0].StartsWith("lines=", StringComparison.Ordinal)); // Check whether file can be successfully extracted byte[] extractDigest; using (MemoryStream ms = new MemoryStream()) { EncodedFile.ExtractFile(sc, "FolderExample", fileName, ms, null); ms.Position = 0; extractDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, ms); } byte[] originDigest; using (FileStream fs = new FileStream(originFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { originDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, fs); } Assert.IsTrue(originDigest.SequenceEqual(extractDigest)); } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } if (File.Exists(destScript)) { File.Delete(destScript); } } } Template("Type1.jpg", EncodedFile.EncodeMode.ZLib); // Type 1 Template("Type2.7z", EncodedFile.EncodeMode.Raw); // Type 2 Template("Type3.pdf", EncodedFile.EncodeMode.XZ); // Type 3 Template("PEBakeryAlphaMemory.jpg", EncodedFile.EncodeMode.ZLib); }
public void Encode() { const string folderName = "FolderExample"; EngineState s = EngineTests.CreateEngineState(); string srcDir = StringEscaper.Preprocess(s, Path.Combine("%TestBench%", "EncodedFile")); string blankScript = Path.Combine(srcDir, "Blank.script"); string destDir = Path.GetTempFileName(); try { File.Delete(destDir); Directory.CreateDirectory(destDir); string destScript = Path.Combine(destDir, Path.GetFileName(Path.GetRandomFileName()) + ".script"); void SingleTemplate(string rawCode, string srcFileName, ErrorCheck check = ErrorCheck.Success) { File.Copy(blankScript, destScript, true); EngineTests.Eval(s, rawCode, CodeType.Encode, check); if (check == ErrorCheck.Success || check == ErrorCheck.Warning) { string srcFile = Path.Combine(srcDir, srcFileName); Script sc = s.Project.LoadScriptRuntime(destScript, new LoadScriptRuntimeOptions()); // Check whether file was successfully encoded Assert.IsTrue(sc.Sections.ContainsKey(ScriptSection.Names.EncodedFolders)); string[] folders = sc.Sections[ScriptSection.Names.EncodedFolders].Lines .Where(x => !x.Equals(string.Empty, StringComparison.Ordinal)) .ToArray(); Assert.IsTrue(folders.Length == 2); Assert.IsTrue(folders[0].Equals(folderName, StringComparison.Ordinal)); Assert.IsTrue(sc.Sections.ContainsKey(folderName)); string[] fileInfos = sc.Sections[folderName].Lines .Where(x => !x.Equals(string.Empty, StringComparison.Ordinal)) .ToArray(); Assert.IsTrue(fileInfos[0].StartsWith($"{srcFileName}=", StringComparison.Ordinal)); Assert.IsTrue(sc.Sections.ContainsKey(ScriptSection.Names.GetEncodedSectionName(folderName, srcFileName))); string[] encodedFile = sc.Sections[ScriptSection.Names.GetEncodedSectionName(folderName, srcFileName)].Lines .Where(x => x.Length != 0) .ToArray(); Assert.IsTrue(1 < encodedFile.Length); Assert.IsTrue(encodedFile[0].StartsWith("lines=", StringComparison.Ordinal)); // Check whether file can be successfully extracted byte[] extractDigest; using (MemoryStream ms = new MemoryStream()) { EncodedFile.ExtractFile(sc, folderName, srcFileName, ms, null); ms.Position = 0; extractDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, ms); } byte[] originDigest; using (FileStream fs = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { originDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, fs); } Assert.IsTrue(originDigest.SequenceEqual(extractDigest)); } } SingleTemplate($@"Encode,{destScript},{folderName},{srcDir}\Type1.jpg,Deflate", "Type1.jpg"); // Type 1 SingleTemplate($@"Encode,{destScript},{folderName},{srcDir}\Type2.7z,None", "Type2.7z"); // Type 2 SingleTemplate($@"Encode,{destScript},{folderName},{srcDir}\Type3.pdf,LZMA2", "Type3.pdf"); // Type 3 SingleTemplate($@"Encode,{destScript},{folderName},{srcDir}\PEBakeryAlphaMemory.jpg", "PEBakeryAlphaMemory.jpg"); } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } } }