Exemplo n.º 1
0
        public static List <LogInfo> DirMake(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_DirMake));
            CodeInfo_DirMake info = cmd.Info as CodeInfo_DirMake;

            string destDir = StringEscaper.Preprocess(s, info.DestDir);

            // Path Security Check
            if (StringEscaper.PathSecurityCheck(destDir, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            // DestPath cannot be file
            if (File.Exists(destDir))
            {
                logs.Add(new LogInfo(LogState.Error, $"File [{destDir}] already exists"));
                return(logs);
            }

            if (Directory.Exists(destDir))
            {
                logs.Add(new LogInfo(LogState.Ignore, $"Directory [{destDir}] already exists"));
            }
            else
            {
                Directory.CreateDirectory(destDir);
                logs.Add(new LogInfo(LogState.Success, $"Created Directory [{destDir}]"));
            }

            return(logs);
        }
Exemplo n.º 2
0
        public static List <LogInfo> IniMerge(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_IniMerge));
            CodeInfo_IniMerge info = cmd.Info as CodeInfo_IniMerge;

            string srcFile  = StringEscaper.Preprocess(s, info.SrcFile);
            string destFile = StringEscaper.Preprocess(s, info.DestFile);

            if (StringEscaper.PathSecurityCheck(destFile, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            bool result = Ini.Merge(srcFile, destFile);

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"[{srcFile}] merged into [{destFile}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not merge [{srcFile}] into [{destFile}]", cmd));
            }


            return(logs);
        }
Exemplo n.º 3
0
        public static List <LogInfo> IniDeleteSection(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_IniDeleteSection));
            CodeInfo_IniDeleteSection info = cmd.Info as CodeInfo_IniDeleteSection;

            string fileName    = StringEscaper.Preprocess(s, info.FileName);
            string sectionName = StringEscaper.Preprocess(s, info.Section); // WB082 : 여기 값은 변수 Expand 안한다.

            if (sectionName.Equals(string.Empty, StringComparison.Ordinal))
            {
                throw new InvalidCodeCommandException("Section name cannot be empty", cmd);
            }

            if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            bool result = Ini.DeleteSection(fileName, sectionName);

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"Section [{sectionName}] deleted from [{fileName}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not delete section [{sectionName}] from [{fileName}]", cmd));
            }
            return(logs);
        }
Exemplo n.º 4
0
        public static List <LogInfo> DirMake(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_DirMake info = cmd.Info.Cast <CodeInfo_DirMake>();

            string destDir = StringEscaper.Preprocess(s, info.DestDir);

            // Path Security Check
            if (!StringEscaper.PathSecurityCheck(destDir, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            // DestPath cannot be file
            if (File.Exists(destDir))
            {
                return(LogInfo.LogErrorMessage(logs, $"File [{destDir}] already exists"));
            }

            if (Directory.Exists(destDir))
            {
                logs.Add(new LogInfo(LogState.Ignore, $"Directory [{destDir}] already exists"));
            }
            else
            {
                Directory.CreateDirectory(destDir);
                logs.Add(new LogInfo(LogState.Success, $"Created Directory [{destDir}]"));
            }

            return(logs);
        }
Exemplo n.º 5
0
        public void PathSecurityCheck_3()
        {
            string windir = Environment.GetEnvironmentVariable("ProgramFiles");
            string path   = Path.Combine(windir, "System32", "notepad.exe");

            Assert.IsFalse(StringEscaper.PathSecurityCheck(path, out string errorMsg));
        }
Exemplo n.º 6
0
        public static List <LogInfo> IniMerge(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniMerge info = cmd.Info.Cast <CodeInfo_IniMerge>();

            string srcFile  = StringEscaper.Preprocess(s, info.SrcFile);
            string destFile = StringEscaper.Preprocess(s, info.DestFile);

            Debug.Assert(srcFile != null, $"{nameof(srcFile)} != null");
            Debug.Assert(destFile != null, $"{nameof(destFile)} != null");

            if (!StringEscaper.PathSecurityCheck(destFile, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            bool result = IniReadWriter.Merge(srcFile, destFile);

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"[{srcFile}] merged into [{destFile}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not merge [{srcFile}] into [{destFile}]", cmd));
            }

            return(logs);
        }
Exemplo n.º 7
0
        public static List <LogInfo> IniDeleteSection(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniDeleteSection info = cmd.Info.Cast <CodeInfo_IniDeleteSection>();

            string fileName = StringEscaper.Preprocess(s, info.FileName);
            string section  = StringEscaper.Preprocess(s, info.Section);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");
            Debug.Assert(section != null, $"{nameof(section)} != null");

            if (section.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
            }

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            bool result = IniReadWriter.DeleteSection(fileName, section);

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"Section [{section}] deleted from [{fileName}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not delete section [{section}] from [{fileName}]", cmd));
            }
            return(logs);
        }
Exemplo n.º 8
0
        public void PathSecurityCheck()
        {
            void Template(string path, bool expected)
            {
                bool result = StringEscaper.PathSecurityCheck(path, out _);

                Assert.AreEqual(expected, result);
            }

            string normalDir = FileHelper.GetTempDir();

            try
            {
                // Valid paths
                Template(Path.Combine(normalDir, "PEBakery.exe"), true);
                Template(Path.Combine(normalDir, "Wildcard.*"), true);
                Template(Path.Combine(normalDir, "Wild*.???"), true);
            }
            finally
            {
                if (Directory.Exists(normalDir))
                {
                    Directory.Delete(normalDir, true);
                }
            }

            // Valid paths
            Template("C:\\", true);
            Template("Wildcard.*", true);
            Template("Wild*.???", true);
            Template(string.Empty, true);

            // Invalid paths
            Template("*\\program.exe", false);

            // %WinDir%
            string winDir = Environment.GetEnvironmentVariable("WinDir");

            Assert.IsNotNull(winDir);
            Template(Path.Combine(winDir, "System32", "notepad.exe"), false);

            // %ProgramFiles%
            string programFiles = Environment.GetEnvironmentVariable("ProgramFiles");

            Assert.IsNotNull(programFiles);
            Template(Path.Combine(programFiles, "PEBakery", "PEBakery.ini"), false);

            // %ProgramFiles(x86)%
            switch (RuntimeInformation.ProcessArchitecture)
            {
            // Not sure about ARM64, please submit an issue/PR if anyone have ARM64 Windows device!
            case Architecture.Arm64:
            case Architecture.X64:
                // Only in 64bit process
                string programFiles86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
                Assert.IsNotNull(programFiles86);
                Template(Path.Combine(programFiles86, "PEBakery", "PEBakery.ini"), false);
                break;
            }
        }
Exemplo n.º 9
0
        public static List <LogInfo> Decompress(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_Decompress info = cmd.Info.Cast <CodeInfo_Decompress>();

            #region Event Handlers
            void ReportDecompressProgress(object sender, ProgressEventArgs e)
            {
                s.MainViewModel.BuildCommandProgressValue = e.PercentDone;
                s.MainViewModel.BuildCommandProgressText  = $"Decompressing... ({e.PercentDone}%)";
            }

            #endregion

            string srcArchive = StringEscaper.Preprocess(s, info.SrcArchive);
            string destDir    = StringEscaper.Preprocess(s, info.DestDir);

            // Path Security Check
            if (!StringEscaper.PathSecurityCheck(destDir, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            // Does SrcArchive exist?
            if (!File.Exists(srcArchive))
            {
                return(LogInfo.LogErrorMessage(logs, $"Cannot find [{srcArchive}]"));
            }

            // Check if file or directory exist under name of destDir
            if (!Directory.Exists(destDir))
            {
                if (File.Exists(destDir))
                {
                    return(LogInfo.LogErrorMessage(logs, $"[{destDir}] should be a directory, not a file"));
                }

                Directory.CreateDirectory(destDir);
            }

            using (SevenZipExtractor extractor = new SevenZipExtractor(srcArchive))
            {
                extractor.Extracting += ReportDecompressProgress;
                s.MainViewModel.SetBuildCommandProgress("Decompress Progress");
                try
                {
                    extractor.ExtractArchive(destDir);
                }
                finally
                {
                    extractor.Extracting -= ReportDecompressProgress;
                    s.MainViewModel.ResetBuildCommandProgress();
                }
            }

            logs.Add(new LogInfo(LogState.Success, $"[{srcArchive}] decompressed to [{destDir}]"));
            return(logs);
        }
Exemplo n.º 10
0
        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);
        }
Exemplo n.º 11
0
        public static List <LogInfo> TXTReplaceOp(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>(8);

            CodeInfo_TXTReplaceOp infoOp = cmd.Info.Cast <CodeInfo_TXTReplaceOp>();

            CodeInfo_TXTReplace firstInfo = infoOp.Infos[0];
            string fileName = StringEscaper.Preprocess(s, firstInfo.FileName);

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            if (!File.Exists(fileName))
            {
                return(LogInfo.LogErrorMessage(logs, $"File [{fileName}] does not exist"));
            }

            List <(CodeCommand, string, string)> prepReplace = new List <(CodeCommand, string, string)>();

            // foreach (CodeInfo_TXTReplace info in infoOp.Infos)
            foreach (CodeCommand subCmd in infoOp.Cmds)
            {
                CodeInfo_TXTReplace info = subCmd.Info.Cast <CodeInfo_TXTReplace>();

                string oldStr = StringEscaper.Preprocess(s, info.OldStr);
                string newStr = StringEscaper.Preprocess(s, info.NewStr);

                prepReplace.Add((subCmd, oldStr, newStr));
            }

            Encoding encoding = EncodingHelper.DetectBom(fileName);

            string tempPath = FileHelper.GetTempFile();
            string txtStr;

            using (StreamReader r = new StreamReader(fileName, encoding, false))
            {
                txtStr = r.ReadToEnd();
            }

            foreach ((CodeCommand subCmd, string oldStr, string newStr) in prepReplace)
            {
                txtStr = StringHelper.ReplaceEx(txtStr, oldStr, newStr, StringComparison.OrdinalIgnoreCase);
                logs.Add(new LogInfo(LogState.Success, $"Replaced [{oldStr}] with [{newStr}]", subCmd));
            }

            using (StreamWriter w = new StreamWriter(tempPath, false, encoding))
            {
                w.Write(txtStr);
            }
            logs.Add(new LogInfo(LogState.Success, $"Replaced [{prepReplace.Count}] strings from [{fileName}]"));

            FileHelper.FileReplaceEx(tempPath, fileName);

            return(logs);
        }
Exemplo n.º 12
0
        public void PathSecurityCheck_2()
        {
            string windir = Environment.GetEnvironmentVariable("windir");

            Assert.IsNotNull(windir);
            string path = Path.Combine(windir, "System32", "notepad.exe");

            Assert.IsFalse(StringEscaper.PathSecurityCheck(path, out _));
        }
Exemplo n.º 13
0
 public void PathSecurityCheck_4()
 {
     if (Environment.Is64BitProcess)
     { // Only in 64bit process
         string windir = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
         string path   = Path.Combine(windir, "System32", "notepad.exe");
         Assert.IsFalse(StringEscaper.PathSecurityCheck(path, out string errorMsg));
     }
 }
Exemplo n.º 14
0
        public static List <LogInfo> IniAddSectionOp(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_IniAddSectionOp));
            CodeInfo_IniAddSectionOp infoOp = cmd.Info as CodeInfo_IniAddSectionOp;

            string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName);

            if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            string[] sections = new string[infoOp.Cmds.Count];
            for (int i = 0; i < sections.Length; i++)
            {
                CodeInfo_IniAddSection info = infoOp.Infos[i];

                string sectionName = StringEscaper.Preprocess(s, info.Section); // WB082 : 여기 값은 변수 Expand 안한다.
                if (sectionName.Equals(string.Empty, StringComparison.Ordinal))
                {
                    throw new InvalidCodeCommandException("Section name cannot be empty", cmd);
                }

                sections[i] = sectionName;
            }

            string dirPath = Path.GetDirectoryName(fileName);

            if (Directory.Exists(dirPath) == false)
            {
                Directory.CreateDirectory(dirPath);
            }

            bool result = Ini.AddSections(fileName, sections);

            if (result)
            {
                for (int i = 0; i < sections.Length; i++)
                {
                    logs.Add(new LogInfo(LogState.Success, $"Section [{sections[i]}] added", infoOp.Cmds[i]));
                }
                logs.Add(new LogInfo(LogState.Success, $"Added [{sections.Length}] sections to [{fileName}]", cmd));
            }
            else
            {
                for (int i = 0; i < sections.Length; i++)
                {
                    logs.Add(new LogInfo(LogState.Error, $"Could not add section [{sections[i]}]", infoOp.Cmds[i]));
                }
                logs.Add(new LogInfo(LogState.Error, $"Could not add [{sections.Length}] sections to [{fileName}]", cmd));
            }

            return(logs);
        }
Exemplo n.º 15
0
        public static List <LogInfo> FileRename(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_FileRename info = cmd.Info.Cast <CodeInfo_FileRename>();

            string srcPath  = StringEscaper.Preprocess(s, info.SrcPath);
            string destPath = StringEscaper.Preprocess(s, info.DestPath);

            // Path Security Check
            if (!StringEscaper.PathSecurityCheck(destPath, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            if (!File.Exists(srcPath))
            {
                // Check if srcPath is directory
                if (!Directory.Exists(srcPath))
                {
                    return(LogInfo.LogErrorMessage(logs, $"File [{srcPath}] does not exist"));
                }

                if (!s.CompatFileRenameCanMoveDir)
                {
                    return(LogInfo.LogErrorMessage(logs, $"[{srcPath}] is a directory, not a file"));
                }

                if (Directory.Exists(destPath))
                {
                    string destFullPath = Path.Combine(destPath, Path.GetFileName(srcPath));

                    Directory.Move(srcPath, destFullPath);
                    logs.Add(new LogInfo(LogState.Success, $"Directory [{srcPath}] moved to [{destFullPath}]"));
                    return(logs);
                }

                Directory.Move(srcPath, destPath);
                logs.Add(new LogInfo(LogState.Success, $"Directory [{srcPath}] moved to [{destPath}]"));
                return(logs);
            }

            File.SetAttributes(srcPath, FileAttributes.Normal);
            File.Move(srcPath, destPath);

            if (cmd.Type == CodeType.FileRename)
            {
                logs.Add(new LogInfo(LogState.Success, $"File [{srcPath}] renamed to [{destPath}]"));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Success, $"File [{srcPath}] moved to [{destPath}]"));
            }

            return(logs);
        }
Exemplo n.º 16
0
        public static List <LogInfo> IniDeleteSectionOp(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniDeleteSectionOp infoOp = cmd.Info.Cast <CodeInfo_IniDeleteSectionOp>();

            string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            string[] sections = new string[infoOp.Cmds.Count];
            for (int i = 0; i < sections.Length; i++)
            {
                CodeInfo_IniDeleteSection info = infoOp.Infos[i];

                string sectionName = StringEscaper.Preprocess(s, info.Section); // WB082 : 여기 값은 변수 Expand 안한다.
                if (sectionName.Length == 0)
                {
                    return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
                }

                sections[i] = sectionName;
            }

            bool[] results = IniReadWriter.DeleteSections(fileName, sections);
            int    success = results.Count(x => x);
            int    failure = results.Count(x => !x);

            for (int i = 0; i < sections.Length; i++)
            {
                if (results[i])
                {
                    logs.Add(new LogInfo(LogState.Success, $"Section [{sections[i]}] deleted", infoOp.Cmds[i]));
                }
                else
                {
                    logs.Add(new LogInfo(LogState.Error, $"Could not delete section [{sections[i]}]", infoOp.Cmds[i]));
                }
            }

            if (0 < success)
            {
                logs.Add(new LogInfo(LogState.Success, $"Deleted [{success}] sections from [{fileName}]", cmd));
            }
            if (0 < failure)
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not delete [{failure}] sections from [{fileName}]", cmd));
            }

            return(logs);
        }
Exemplo n.º 17
0
        public static List <LogInfo> TXTReplace(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_TXTReplace info = cmd.Info.Cast <CodeInfo_TXTReplace>();

            string fileName = StringEscaper.Preprocess(s, info.FileName);
            string oldStr   = StringEscaper.Preprocess(s, info.OldStr);
            string newStr   = StringEscaper.Preprocess(s, info.NewStr);

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            if (!File.Exists(fileName))
            {
                return(LogInfo.LogErrorMessage(logs, $"File [{fileName}] does not exist"));
            }

            // Detect encoding of text. If text does not exists, create blank file (ANSI)
            Encoding encoding;

            if (File.Exists(fileName))
            {
                encoding = EncodingHelper.SmartDetectEncoding(fileName, () =>
                {
                    return(EncodingHelper.IsActiveCodePageCompatible(info.OldStr) &&
                           EncodingHelper.IsActiveCodePageCompatible(info.NewStr));
                });
            }
            else
            {
                encoding = EncodingHelper.DefaultAnsi;
            }

            string tempPath = FileHelper.GetTempFile();
            string txtStr;

            using (StreamReader r = new StreamReader(fileName, encoding, false))
            {
                txtStr = r.ReadToEnd();
            }

            using (StreamWriter w = new StreamWriter(tempPath, false, encoding))
            {
                txtStr = StringHelper.ReplaceEx(txtStr, oldStr, newStr, StringComparison.OrdinalIgnoreCase);
                w.Write(txtStr);
            }
            FileHelper.FileReplaceEx(tempPath, fileName);

            logs.Add(new LogInfo(LogState.Success, $"Replaced [{oldStr}] with [{newStr}]", cmd));

            return(logs);
        }
Exemplo n.º 18
0
        public static List <LogInfo> IniWriteTextLine(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniWriteTextLine info = cmd.Info.Cast <CodeInfo_IniWriteTextLine>();

            string fileName = StringEscaper.Preprocess(s, info.FileName);
            string section  = StringEscaper.Preprocess(s, info.Section);
            string line     = StringEscaper.Preprocess(s, info.Line);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");
            Debug.Assert(section != null, $"{nameof(section)} != null");
            Debug.Assert(line != null, $"{nameof(line)} != null");

            if (section.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
            }

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            string dirPath = Path.GetDirectoryName(fileName);

            if (dirPath == null)
            {
                throw new InternalException("Internal Logic Error at IniWriteTextLine");
            }
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            // If a dest file does not exist, create an empty file to force ANSI encoding as default in IniReadWriter.
            if (!File.Exists(fileName))
            {
                File.Create(fileName).Dispose();
            }

            bool result = IniReadWriter.WriteRawLine(fileName, section, line, info.Append);

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"Line [{line}] wrote to [{fileName}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not write line [{line}] to [{fileName}]", cmd));
            }

            return(logs);
        }
Exemplo n.º 19
0
        public static List <LogInfo> IniWrite(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniWrite info = cmd.Info.Cast <CodeInfo_IniWrite>();

            string fileName    = StringEscaper.Preprocess(s, info.FileName);
            string sectionName = StringEscaper.Preprocess(s, info.Section);
            string key         = StringEscaper.Preprocess(s, info.Key);
            string value       = StringEscaper.Preprocess(s, info.Value);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");
            Debug.Assert(sectionName != null, $"{nameof(sectionName)} != null");
            Debug.Assert(key != null, $"{nameof(key)} != null");
            Debug.Assert(value != null, $"{nameof(value)} != null");

            if (sectionName.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
            }
            if (key.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Key name cannot be empty"));
            }

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            string dirPath = Path.GetDirectoryName(fileName);

            if (dirPath == null)
            {
                throw new InternalException("Internal Logic Error at IniWrite");
            }
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            bool result = IniReadWriter.WriteKey(fileName, sectionName, key, value);

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"Key [{key}] and it's value [{value}] written to [{fileName}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not write key [{key}] and it's value [{value}] to [{fileName}]", cmd));
            }

            return(logs);
        }
Exemplo n.º 20
0
        public static List <LogInfo> TXTReplaceOp(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_TXTReplaceOp));
            CodeInfo_TXTReplaceOp infoOp = cmd.Info as CodeInfo_TXTReplaceOp;

            string fileName = StringEscaper.Preprocess(s, infoOp.InfoList[0].FileName);

            if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            if (File.Exists(fileName) == false)
            {
                logs.Add(new LogInfo(LogState.Error, $"File [{fileName}] not exists"));
                return(logs);
            }

            List <Tuple <string, string> > prepReplace = new List <Tuple <string, string> >();

            foreach (CodeInfo_TXTReplace info in infoOp.InfoList)
            {
                string oldStr = StringEscaper.Preprocess(s, info.OldStr);
                string newStr = StringEscaper.Preprocess(s, info.NewStr);
                prepReplace.Add(new Tuple <string, string>(oldStr, newStr));
            }

            Encoding encoding = FileHelper.DetectTextEncoding(fileName);

            string tempPath = Path.GetTempFileName();

            using (StreamReader reader = new StreamReader(fileName, encoding))
                using (StreamWriter writer = new StreamWriter(tempPath, false, encoding))
                {
                    string str = reader.ReadToEnd();
                    foreach (var tup in prepReplace)
                    {
                        string oldStr = tup.Item1;
                        string newStr = tup.Item2;

                        str = StringHelper.ReplaceEx(str, oldStr, newStr, StringComparison.OrdinalIgnoreCase);
                        logs.Add(new LogInfo(LogState.Success, $"Replaced [{oldStr}] with [{newStr}]"));
                    }
                    writer.Write(str);
                }
            FileHelper.FileReplaceEx(tempPath, fileName);

            return(logs);
        }
Exemplo n.º 21
0
        public static List <LogInfo> PathMove(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_PathMove));
            CodeInfo_PathMove info = cmd.Info as CodeInfo_PathMove;

            string srcPath  = StringEscaper.Preprocess(s, info.SrcPath);
            string destPath = StringEscaper.Preprocess(s, info.DestPath);

            // Path Security Check
            if (StringEscaper.PathSecurityCheck(destPath, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            // SrcPath must be directory
            if (File.Exists(srcPath))
            {
                File.SetAttributes(srcPath, FileAttributes.Normal);
                File.Move(srcPath, destPath);
                logs.Add(new LogInfo(LogState.Success, $"File [{srcPath}] moved to [{destPath}]"));
            }
            else if (Directory.Exists(srcPath))
            {
                // DestPath must be directory
                if (File.Exists(destPath))
                {
                    logs.Add(new LogInfo(LogState.Error, $"[{destPath}] is a file, not a directory"));
                    return(logs);
                }

                if (Directory.Exists(destPath))
                {
                    string destFullPath = Path.Combine(destPath, Path.GetFileName(srcPath));
                    Directory.Move(srcPath, destFullPath);
                    logs.Add(new LogInfo(LogState.Success, $"Directory [{srcPath}] moved to [{destFullPath}]"));
                }
                else
                {
                    Directory.Move(srcPath, destPath);
                    logs.Add(new LogInfo(LogState.Success, $"Directory [{srcPath}] moved to [{destPath}]"));
                }
            }
            else
            {
                logs.Add(new LogInfo(LogState.Success, $"Path [{srcPath}] does not exist"));
            }

            return(logs);
        }
Exemplo n.º 22
0
        public static List <LogInfo> IniDelete(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniDelete info = cmd.Info.Cast <CodeInfo_IniDelete>();

            string fileName    = StringEscaper.Preprocess(s, info.FileName);
            string sectionName = StringEscaper.Preprocess(s, info.Section);
            string key         = StringEscaper.Preprocess(s, info.Key);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");
            Debug.Assert(sectionName != null, $"{nameof(sectionName)} != null");
            Debug.Assert(key != null, $"{nameof(key)} != null");

            if (sectionName.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
            }
            if (key.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Key name cannot be empty"));
            }

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            bool result;

            if (s.CompatAutoCompactIniWriteCommand)
            {
                result = IniReadWriter.DeleteCompactKey(fileName, sectionName, key);
            }
            else
            {
                result = IniReadWriter.DeleteKey(fileName, sectionName, key);
            }

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"Key [{key}] deleted from [{fileName}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Ignore, $"Could not delete key [{key}] from [{fileName}]", cmd));
            }

            return(logs);
        }
Exemplo n.º 23
0
        public static List <LogInfo> DirMove(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_DirMove info = cmd.Info.Cast <CodeInfo_DirMove>();

            string srcDir   = StringEscaper.Preprocess(s, info.SrcDir);
            string destPath = StringEscaper.Preprocess(s, info.DestPath);

            // Path Security Check
            if (!StringEscaper.PathSecurityCheck(destPath, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            // SrcPath must be directory
            // WB082 does not check this, so file can be moved with DirMove
            if (File.Exists(srcDir))
            {
                return(LogInfo.LogErrorMessage(logs, $"[{srcDir}] is a file, not a directory"));
            }

            // DestPath must be directory
            if (File.Exists(destPath))
            {
                return(LogInfo.LogErrorMessage(logs, $"[{destPath}] is a file, not a directory"));
            }

            if (Directory.Exists(destPath))
            {
                string srcDirName = Path.GetFileName(srcDir);
                if (srcDirName == null)
                {
                    throw new InternalException("Internal Logic Error at DirMove");
                }
                string destFullPath = Path.Combine(destPath, srcDirName);

                Directory.Move(srcDir, destFullPath);

                logs.Add(new LogInfo(LogState.Success, $"Directory [{srcDir}] moved to [{destFullPath}]"));
            }
            else
            {
                Directory.Move(srcDir, destPath);

                logs.Add(new LogInfo(LogState.Success, $"Directory [{srcDir}] moved to [{destPath}]"));
            }

            return(logs);
        }
Exemplo n.º 24
0
        public static List <LogInfo> TXTDelSpaces(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_TXTDelSpaces));
            CodeInfo_TXTDelSpaces info = cmd.Info as CodeInfo_TXTDelSpaces;

            string fileName = StringEscaper.Preprocess(s, info.FileName);

            if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            if (File.Exists(fileName) == false)
            {
                logs.Add(new LogInfo(LogState.Error, $"File [{fileName}] not exists"));
                return(logs);
            }

            Encoding encoding = FileHelper.DetectTextEncoding(fileName);

            int    i        = 0;
            string tempPath = Path.GetTempFileName();

            using (StreamReader reader = new StreamReader(fileName, encoding))
                using (StreamWriter writer = new StreamWriter(tempPath, false, encoding))
                {
                    string srcLine;
                    while ((srcLine = reader.ReadLine()) != null)
                    {
                        // WB082 delete spaces only if spaces are placed in front of line.
                        // Same with C#'s string.TrimStart().
                        int count = StringHelper.CountOccurrences(srcLine, " ");
                        if (0 < count)
                        {
                            i++;
                            srcLine = srcLine.TrimStart();
                        }
                        writer.WriteLine(srcLine);
                    }
                }
            FileHelper.FileReplaceEx(tempPath, fileName);

            logs.Add(new LogInfo(LogState.Success, $"Deleted [{i}] spaces"));

            return(logs);
        }
Exemplo n.º 25
0
        public static List <LogInfo> TXTDelLine(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_TXTDelLine info = cmd.Info.Cast <CodeInfo_TXTDelLine>();

            string fileName   = StringEscaper.Preprocess(s, info.FileName);
            string deleteLine = StringEscaper.Preprocess(s, info.DeleteLine);

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            if (!File.Exists(fileName))
            {
                return(LogInfo.LogErrorMessage(logs, $"File [{fileName}] does not exist"));
            }

            // Detect encoding of text.
            Encoding encoding = EncodingHelper.SmartDetectEncoding(fileName, deleteLine);

            int    count    = 0;
            string tempPath = FileHelper.GetTempFile();

            using (StreamReader r = new StreamReader(fileName, encoding, false))
                using (StreamWriter w = new StreamWriter(tempPath, false, encoding))
                {
                    string srcLine;
                    while ((srcLine = r.ReadLine()) != null)
                    {
                        // Strange enough, WB082 treat [deleteLine] as case sensitive string.
                        if (srcLine.StartsWith(deleteLine, StringComparison.Ordinal))
                        {
                            count++;
                        }
                        else
                        {
                            w.WriteLine(srcLine);
                        }
                    }
                }
            FileHelper.FileReplaceEx(tempPath, fileName);

            logs.Add(new LogInfo(LogState.Success, $"Line [{deleteLine}] deleted from [{fileName}]"));
            logs.Add(new LogInfo(LogState.Success, $"Deleted [{count}] lines"));

            return(logs);
        }
Exemplo n.º 26
0
        public static List <LogInfo> DirMove(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_DirMove));
            CodeInfo_DirMove info = cmd.Info as CodeInfo_DirMove;

            string srcDir   = StringEscaper.Preprocess(s, info.SrcDir);
            string destPath = StringEscaper.Preprocess(s, info.DestPath);

            // Path Security Check
            if (StringEscaper.PathSecurityCheck(destPath, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            // SrcPath must be directory
            // WB082 does not check this, so file can be moved with DirMove
            if (File.Exists(srcDir))
            {
                logs.Add(new LogInfo(LogState.Error, $"[{srcDir}] is a file, not a directory"));
                return(logs);
            }

            // DestPath must be directory
            if (File.Exists(destPath))
            {
                logs.Add(new LogInfo(LogState.Error, $"[{destPath}] is a file, not a directory"));
                return(logs);
            }

            if (Directory.Exists(destPath))
            {
                string destFullPath = Path.Combine(destPath, Path.GetFileName(srcDir));

                Directory.Move(srcDir, destFullPath);

                logs.Add(new LogInfo(LogState.Success, $"Directory [{srcDir}] moved to [{destFullPath}]"));
            }
            else
            {
                Directory.Move(srcDir, destPath);

                logs.Add(new LogInfo(LogState.Success, $"Directory [{srcDir}] moved to [{destPath}]"));
            }

            return(logs);
        }
Exemplo n.º 27
0
        public static List <LogInfo> TXTDelEmptyLines(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_TXTDelEmptyLines));
            CodeInfo_TXTDelEmptyLines info = cmd.Info as CodeInfo_TXTDelEmptyLines;

            string fileName = StringEscaper.Preprocess(s, info.FileName);

            if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            if (File.Exists(fileName) == false)
            {
                logs.Add(new LogInfo(LogState.Error, $"File [{fileName}] not exists"));
                return(logs);
            }

            Encoding encoding = FileHelper.DetectTextEncoding(fileName);

            int    i        = 0;
            string tempPath = Path.GetTempFileName();

            using (StreamReader reader = new StreamReader(fileName, encoding))
                using (StreamWriter writer = new StreamWriter(tempPath, false, encoding))
                {
                    string lineFromSrc;
                    while ((lineFromSrc = reader.ReadLine()) != null)
                    {
                        if (lineFromSrc.Equals(string.Empty, StringComparison.Ordinal))
                        {
                            i++;
                        }
                        else
                        {
                            writer.WriteLine(lineFromSrc);
                        }
                    }
                }
            FileHelper.FileReplaceEx(tempPath, fileName);

            logs.Add(new LogInfo(LogState.Success, $"Deleted [{i}] empty lines"));

            return(logs);
        }
Exemplo n.º 28
0
        public static List <LogInfo> TXTDelLine(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_TXTDelLine));
            CodeInfo_TXTDelLine info = cmd.Info as CodeInfo_TXTDelLine;

            string fileName   = StringEscaper.Preprocess(s, info.FileName);
            string deleteLine = StringEscaper.Preprocess(s, info.DeleteLine);

            if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            if (File.Exists(fileName) == false)
            {
                logs.Add(new LogInfo(LogState.Error, $"File [{fileName}] not exists"));
                return(logs);
            }

            Encoding encoding = FileHelper.DetectTextEncoding(fileName);

            int    i        = 0;
            string tempPath = Path.GetTempFileName();

            using (StreamReader reader = new StreamReader(fileName, encoding))
                using (StreamWriter writer = new StreamWriter(tempPath, false, encoding))
                {
                    string srcLine;
                    while ((srcLine = reader.ReadLine()) != null)
                    {
                        // Strange enough, WB082 treat [deleteLine] as case sensitive string.
                        if (srcLine.StartsWith(deleteLine, StringComparison.Ordinal))
                        {
                            i++;
                            continue;
                        }
                        writer.WriteLine(srcLine);
                    }
                }
            FileHelper.FileReplaceEx(tempPath, fileName);

            logs.Add(new LogInfo(LogState.Success, $"Deleted [{i}] lines from [{fileName}]"));

            return(logs);
        }
Exemplo n.º 29
0
        public static List <LogInfo> CopyOrExpand(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_CopyOrExpand));
            CodeInfo_CopyOrExpand info = cmd.Info as CodeInfo_CopyOrExpand;

            string srcFile  = StringEscaper.Preprocess(s, info.SrcFile);
            string destPath = StringEscaper.Preprocess(s, info.DestPath);

            // Path Security Check
            if (StringEscaper.PathSecurityCheck(destPath, out string errorMsg) == false)
            {
                logs.Add(new LogInfo(LogState.Error, errorMsg));
                return(logs);
            }

            // Check srcFile contains wildcard
            if (srcFile.IndexOfAny(new char[] { '*', '?' }) == -1)
            { // No Wildcard
                InternalCopyOrExpand(s, logs, info, srcFile, destPath);
            }
            else
            { // With Wildcard
                string srcDirToFind = FileHelper.GetDirNameEx(srcFile);

                string[] files = FileHelper.GetFilesEx(srcDirToFind, Path.GetFileName(srcFile));

                if (0 < files.Length)
                { // One or more file will be copied
                    logs.Add(new LogInfo(LogState.Success, $"[{srcFile}] will be copied to [{destPath}]", cmd));

                    for (int i = 0; i < files.Length; i++)
                    {
                        string f = files[i];
                        InternalCopyOrExpand(s, logs, info, f, destPath);
                    }

                    logs.Add(new LogInfo(LogState.Success, $"[{files.Length}] files copied", cmd));
                }
                else
                { // No file will be copied
                    logs.Add(new LogInfo(info.NoWarn ? LogState.Ignore : LogState.Warning, $"Files match wildcard [{srcFile}] not found", cmd));
                }
            }

            return(logs);
        }
Exemplo n.º 30
0
        public static List <LogInfo> TXTDelSpaces(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_TXTDelSpaces info = cmd.Info.Cast <CodeInfo_TXTDelSpaces>();

            string fileName = StringEscaper.Preprocess(s, info.FileName);

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            if (!File.Exists(fileName))
            {
                return(LogInfo.LogErrorMessage(logs, $"File [{fileName}] does not exist"));
            }

            Encoding encoding = EncodingHelper.DetectEncoding(fileName);

            int    linesTrimmed = 0;
            string tempPath     = FileHelper.GetTempFile();

            using (StreamReader sr = new StreamReader(fileName, encoding, false))
                using (StreamWriter sw = new StreamWriter(tempPath, false, encoding))
                {
                    string srcLine;
                    while ((srcLine = sr.ReadLine()) != null)
                    {
                        int count = StringHelper.CountSubStr(srcLine, " ");
                        if (0 < count)
                        {
                            srcLine = srcLine.Trim();
                            if (!StringHelper.CountSubStr(srcLine, " ").Equals(count)) //only count lines that we actually trimmed
                            {
                                linesTrimmed++;
                            }
                        }
                        sw.WriteLine(srcLine);
                    }
                }
            FileHelper.FileReplaceEx(tempPath, fileName);

            logs.Add(new LogInfo(LogState.Success, $"Deleted leading and trailing spaces from [{linesTrimmed}] lines"));

            return(logs);
        }