示例#1
0
        /*
         * Registry Commands
         */

        /// <summary>
        /// RegHiveLoad,<KeyName>,<HiveFileName>
        ///
        /// Load HiveFile into local machine's key
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        private LogInfo[] RegHiveLoad(BakeryCommand cmd)
        {
            ArrayList logs = new ArrayList();

            // Must-have operand : 2
            if (cmd.Operands.Length < 2)
            {
                throw new InvalidOperandException("Not enough operand");
            }
            else if (2 < cmd.Operands.Length)
            {
                throw new InvalidOperandException("Too many operands");
            }

            string keyName      = cmd.Operands[0];
            string hiveFileName = cmd.Operands[1];

            if (!File.Exists(hiveFileName))
            {
                throw new FileNotFoundException(hiveFileName + " does not exists");
            }

            int ret = RegLoadKey(HKLM, keyName, hiveFileName);

            if (ret == ResultWin32.ERROR_SUCCESS)
            {
                logs.Add(new LogInfo(cmd, string.Concat("Loaded ", hiveFileName, " into HKLM\\", keyName), LogState.Success));
            }
            else
            {
                logs.Add(new LogInfo(cmd, string.Concat("RegLoadKey API returned error : ", ret, " (", ResultWin32.GetErrorName(ret), ")"), LogState.Error));
            }

            return(logs.ToArray(typeof(LogInfo)) as LogInfo[]);
        }
示例#2
0
        /// <summary>
        /// Run,%ScriptFile%,<Section>[,PARAMS]
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public LogInfo[] RunExec(BakeryCommand cmd)
        {
            ArrayList logs = new ArrayList();

            // Necessary operand : 2, optional operand : variable length
            const int necessaryOperandNum = 2;

            if (cmd.Operands.Length < necessaryOperandNum)
            {
                throw new InvalidOperandException("Necessary operands does not exist", cmd);
            }

            // Get necesssary operand
            string pluginFile     = variables.Expand(cmd.Operands[0]);
            string rawPluginFile  = cmd.Operands[0];
            string sectionName    = variables.Expand(cmd.Operands[1]);
            string rawSectoinName = cmd.Operands[1];

            // Get optional operand
            string[] parameters = new string[cmd.Operands.Length - necessaryOperandNum];
            if (necessaryOperandNum < cmd.Operands.Length)
            {
                Array.Copy(cmd.Operands, 2, parameters, 0, cmd.Operands.Length - necessaryOperandNum);
            }

            bool currentPlugin = false;

            if (String.Equals(rawPluginFile, "%PluginFile%", StringComparison.OrdinalIgnoreCase))
            {
                currentPlugin = true;
            }
            else if (String.Equals(rawPluginFile, "%ScriptFile%", StringComparison.OrdinalIgnoreCase))
            {
                currentPlugin = true;
            }

            if (currentPlugin)
            {
                if (!plugins[curPluginIdx].Sections.ContainsKey(sectionName))
                {
                    throw new InvalidOperandException(string.Concat("'", Path.GetFileName(pluginFile), "' does not have section '", sectionName, "'"), cmd);
                }

                // Branch to new section
                returnAddress.Push(new CommandAddress(cmd.Address.section, cmd.Address.line + 1, cmd.Address.secLength));
                nextCommand          = new CommandAddress(plugins[curPluginIdx].Sections[sectionName], 0, plugins[curPluginIdx].Sections[sectionName].SecLines.Length);
                currentSectionParams = parameters;

                // Exec utilizes [Variables] section of the plugin
                if (cmd.Opcode == Opcode.Exec)
                {
                }
            }

            cmd.SectionDepth += 1; // For proper log indentation
            logs.Add(new LogInfo(cmd, string.Concat("Running section '", sectionName, "'"), LogState.Success));

            return(logs.ToArray(typeof(LogInfo)) as LogInfo[]);
        }
示例#3
0
 /// <summary>
 /// Hold command information, with sub command.
 /// </summary>
 /// <param name="rawCode"></param>
 /// <param name="opcode"></param>
 /// <param name="operands"></param>
 /// <param name="subCommand"></param>
 public BakeryCommand(string rawCode, Opcode opcode, string[] operands, BakeryCommand subCommand, int sectionDepth)
 {
     this.rawCode      = rawCode;
     this.opcode       = opcode;
     this.operands     = operands;
     this.subCommand   = subCommand;
     this.sectionDepth = sectionDepth;
 }
示例#4
0
 private void DisplayOperation(BakeryCommand cmd)
 {
     for (int i = 0; i < cmd.SectionDepth; i++)
     {
         Console.Write("  ");
     }
     Console.WriteLine(cmd.RawCode);
 }
示例#5
0
 /// <summary>
 /// Hold command information.
 /// </summary>
 /// <param name="opcode"></param>
 /// <param name="operands"></param>
 /// <param name="optional"></param>
 public BakeryCommand(string rawCode, Opcode opcode, string[] operands)
 {
     this.rawCode      = rawCode;
     this.opcode       = opcode;
     this.operands     = operands;
     this.subCommand   = null;
     this.sectionDepth = 0;
 }
示例#6
0
 /// <summary>
 /// Hold command information, with address and subcommand
 /// </summary>
 /// <param name="opcode"></param>
 /// <param name="operands"></param>
 /// <param name="optional"></param>
 public BakeryCommand(string rawCode, Opcode opcode, string[] operands, CommandAddress address, BakeryCommand subCommand)
 {
     this.rawCode    = rawCode;
     this.opcode     = opcode;
     this.operands   = operands;
     this.address    = address;
     this.subCommand = subCommand;
 }
示例#7
0
 /// <summary>
 /// Hold command information, with address
 /// </summary>
 /// <param name="opcode"></param>
 /// <param name="operands"></param>
 /// <param name="optional"></param>
 public BakeryCommand(string rawCode, Opcode opcode, string[] operands, CommandAddress address, int sectionDepth)
 {
     this.rawCode      = rawCode;
     this.opcode       = opcode;
     this.operands     = operands;
     this.address      = address;
     this.subCommand   = null;
     this.sectionDepth = sectionDepth;
 }
示例#8
0
        /// <summary>
        /// Run array of commands.
        /// </summary>
        /// <param name="nextCommand"></param>
        private void RunCommands()
        {
            while (true)
            {
                if (!(nextCommand.line < nextCommand.secLength)) // End of section
                {
                    currentSectionParams = new string[0];
                    BakeryCommand logCmd = new BakeryCommand("End of section", Opcode.None, new string[0], returnAddress.Count);
                    string        logMsg = string.Concat("Section '", nextCommand.section.SecName, "' End");
                    logger.Write(new LogInfo(logCmd, logMsg, LogState.Infomation));
                    try
                    {
                        nextCommand = returnAddress.Pop();
                        if (!(nextCommand.line < nextCommand.secLength)) // Is return address end of section?
                        {
                            continue;
                        }
                    }
                    catch (InvalidOperationException)
                    { // The Stack<T> is empty, terminate function
                        break;
                    }
                }

                // Fetch instructions
                int    i       = nextCommand.line;
                string rawCode = nextCommand.section.SecLines[i].Trim();

                try
                {
                    currentCommand = ParseCommand(rawCode, new CommandAddress(nextCommand.section, i, nextCommand.secLength));

                    try
                    {
                        ExecuteCommand(currentCommand, logger);
                    }
                    catch (InvalidOpcodeException e)
                    {
                        logger.Write(new LogInfo(e.Command, e.Message, LogState.Error));
                    }
                }
                catch (InvalidOpcodeException e)
                {
                    currentCommand = new BakeryCommand(rawCode, Opcode.Unknown, new string[0]);
                    logger.Write(new LogInfo(e.Command, e.Message, LogState.Error));
                }
                catch (InvalidOperandException e)
                {
                    currentCommand = new BakeryCommand(rawCode, Opcode.Unknown, new string[0]);
                    logger.Write(new LogInfo(e.Command, e.Message, LogState.Error));
                }
                nextCommand.line += 1;
            }

            logger.WriteVariables(variables);
        }
示例#9
0
        private void InternalConstructor(Plugin[] plugins, int pluginIndex, Logger logger)
        {
            this.plugins   = plugins;
            this.logger    = logger;
            this.variables = new BakeryVariables();

            LoadDefaultGlobalVariables();
            curPluginIdx         = pluginIndex;
            currentCommand       = null;
            returnAddress        = new Stack <CommandAddress>();
            currentSectionParams = new string[0];
        }
示例#10
0
        /// <summary>
        /// RegHiveUnload,<KeyName>
        ///
        /// Unload HiveFile from local machine
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        private LogInfo[] RegHiveUnload(BakeryCommand cmd)
        {
            ArrayList logs = new ArrayList();

            string   logResult = string.Empty;
            LogState resState  = LogState.Success;

            // Must-have operand : 2
            if (cmd.Operands.Length < 2)
            {
                throw new InvalidOperandException("Not enough operand");
            }
            else if (2 < cmd.Operands.Length)
            {
                throw new InvalidOperandException("Too many operands");
            }

            string keyName      = cmd.Operands[0];
            string hiveFileName = cmd.Operands[1];

            if (!File.Exists(hiveFileName))
            {
                throw new FileNotFoundException(hiveFileName + " does not exists");
            }

            int ret = RegLoadKey(HKLM, keyName, hiveFileName);

            if (ret != ResultWin32.ERROR_SUCCESS)
            {
                logResult = string.Format("RegLoadKey API returned {0}:{1}", ret, ResultWin32.GetErrorName(ret));
                resState  = LogState.Error;
            }

            logs.Add(new LogInfo(cmd, logResult, resState));
            return(logs.ToArray(typeof(LogInfo)) as LogInfo[]);
        }
示例#11
0
文件: Logger.cs 项目: Variel/PEBakery
 /// <summary>
 /// Forge an log info
 /// </summary>
 /// <param name="command"></param>
 /// <param name="result"></param>
 /// <param name="state"></param>
 public LogInfo(BakeryCommand command, string result, LogState state)
 {
     this.command = command;
     this.result  = result;
     this.state   = state;
 }
示例#12
0
 public PathNotDirException(string message, BakeryCommand command) : base(message)
 {
     this.command = command;
 }
示例#13
0
        /*
         * File Commands
         * Note) Need refactor to support file name longer than 260 length.
         * http://bcl.codeplex.com/releases/view/42783
         * http://alphafs.alphaleonis.com/
         */

        /// <summary>
        /// FileCopy,<SrcFileName>,<DestPath>[,PRESERVE][,NOWARN][,NOREC]
        /// Wildcard supported in <SrcFileName>
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns>LogInfo[]</returns>
        public LogInfo[] FileCopy(BakeryCommand cmd)
        {
            ArrayList logs = new ArrayList();

            // Necessary operand : 2, optional operand : 3
            const int necessaryOperandNum = 2;
            const int optionalOperandNum  = 3;

            if (cmd.Operands.Length < necessaryOperandNum)
            {
                throw new InvalidOperandException("Necessary operands does not exist", cmd);
            }
            else if (necessaryOperandNum + optionalOperandNum < cmd.Operands.Length)
            {
                throw new InvalidOperandException("Too many operands", cmd);
            }

            string srcFileName    = variables.Expand(cmd.Operands[0]);
            string rawSrcFileName = cmd.Operands[0];
            string destPath       = variables.Expand(cmd.Operands[1]);
            string rawDestPath    = cmd.Operands[1];

            // Check srcFileName contains wildcard
            bool srcContainWildcard = true;

            if (srcFileName.IndexOfAny(new char[] { '*', '?' }) == -1) // No wildcard
            {
                srcContainWildcard = false;
            }
            // Check destPath is directory
            bool destPathExists = false;
            bool destPathIsDir  = false;

            if (Directory.Exists(destPath))
            {
                destPathExists = true;
                destPathIsDir  = true;
            }
            else if (File.Exists(destPath))
            {
                destPathExists = true;
            }

            bool preserve = false;
            bool noWarn   = false;
            bool noRec    = false;

            for (int i = necessaryOperandNum; i < cmd.Operands.Length; i++)
            {
                string operand = cmd.Operands[i];
                switch (operand.ToUpper())
                {
                case "PRESERVE":
                    preserve = true;
                    break;

                case "NOWARN":
                    noWarn = true;
                    break;

                case "SHOW":     // for compability with WB082
                    break;

                case "NOREC":     // no recursive wildcard copy
                    noRec = true;
                    break;

                default:
                    throw new InvalidOperandException(string.Concat("Invalid operand ", operand), cmd);
                }
            }

            try
            {
                if (srcContainWildcard)
                {
                    string   srcDirToFind    = Helper.GetDirNameEx(srcFileName);
                    string   rawSrcDirToFind = Helper.GetDirNameEx(rawSrcFileName);
                    string[] listToCopy;
                    if (noRec)
                    {
                        listToCopy = Directory.GetFiles(srcDirToFind, Path.GetFileName(srcFileName));
                    }
                    else
                    {
                        listToCopy = Directory.GetFiles(srcDirToFind, Path.GetFileName(srcFileName), SearchOption.AllDirectories);
                    }
                    foreach (string searchedFilePath in listToCopy)
                    {
                        if (destPathIsDir || !destPathExists)
                        {
                            string rawDestPathDir = Helper.GetDirNameEx(rawDestPath);
                            string destPathTail   = searchedFilePath.Remove(0, srcDirToFind.Length + 1); // 1 for \\
                            string destFullPath   = Path.Combine(Helper.RemoveLastDirChar(destPath), destPathTail);
                            Directory.CreateDirectory(Path.GetDirectoryName(destFullPath));
                            if (File.Exists(destFullPath) && !noWarn)
                            {
                                logs.Add(new LogInfo(cmd, string.Concat(@"'", Path.Combine(rawSrcDirToFind, destPathTail), @"' will be overwritten"), LogState.Warning));
                            }
                            File.Copy(searchedFilePath, destFullPath, !preserve);
                            logs.Add(new LogInfo(cmd, string.Concat(@"'", Path.Combine(rawSrcDirToFind, destPathTail), @"' copied to '", Path.Combine(rawDestPathDir, destPathTail), @"'"), LogState.Success));
                        }
                        else
                        {
                            throw new PathNotDirException("<DestPath> must be directory when using wildcard in <SrcFileName>", cmd);
                        }
                    }
                    if (listToCopy.Length == 0)
                    {
                        logs.Add(new LogInfo(cmd, string.Concat(@"'", rawDestPath, @"' not found"), noWarn ? LogState.Ignore : LogState.Warning));
                    }
                }
                else
                {
                    if (destPathIsDir)
                    {
                        Directory.CreateDirectory(destPath);
                        string rawDestPathDir = Helper.GetDirNameEx(rawDestPath);
                        string destPathTail   = srcFileName.Remove(0, Helper.GetDirNameEx(srcFileName).Length + 1); // 1 for \\
                        string destFullPath   = string.Concat(Helper.RemoveLastDirChar(destPath), Path.DirectorySeparatorChar, destPathTail);
                        if (File.Exists(destFullPath))
                        {
                            logs.Add(new LogInfo(cmd, string.Concat(@"'", Path.Combine(rawDestPathDir, destPathTail), @"' will be overwritten"), noWarn ? LogState.Ignore : LogState.Warning));
                        }

                        File.Copy(srcFileName, destFullPath, !preserve);
                        logs.Add(new LogInfo(cmd, string.Concat(@"'", rawSrcFileName, @"' copied to '", rawDestPath, @"'"), LogState.Success));
                    }
                    else
                    {
                        Directory.CreateDirectory(Helper.GetDirNameEx(destPath));
                        if (destPathExists)
                        {
                            logs.Add(new LogInfo(cmd, string.Concat(@"'", rawDestPath, @"' will be overwritten"), noWarn ? LogState.Ignore : LogState.Warning));
                        }
                        File.Copy(srcFileName, destPath, !preserve);
                        logs.Add(new LogInfo(cmd, string.Concat(@"'", rawSrcFileName, @"' copied to '", rawDestPath, @"'"), LogState.Success));
                    }
                }
            }
            catch (IOException e)
            {
                if (preserve && noWarn)
                {
                    logs.Add(new LogInfo(cmd, string.Concat("Cannot overwrite ", destPath), LogState.Ignore));
                }
                else
                {
                    throw new IOException(e.Message, e);
                }
            }

            return(logs.ToArray(typeof(LogInfo)) as LogInfo[]);
        }
示例#14
0
        /// <summary>
        /// FileCreateBlank,<FileName>[,PRESERVE][,NOWARN][,UTF8 | UTF16LE | UTF16BE | ANSI]
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public LogInfo[] FileCreateBlank(BakeryCommand cmd)
        {
            ArrayList logs = new ArrayList();
            // Necessary operand : 1, optional operand : 3
            const int necessaryOperandNum = 1;
            const int optionalOperandNum  = 3;

            if (cmd.Operands.Length < necessaryOperandNum)
            {
                throw new InvalidOperandException("Necessary operands does not exist", cmd);
            }
            else if (necessaryOperandNum + optionalOperandNum < cmd.Operands.Length)
            {
                throw new InvalidOperandException("Too many operands", cmd);
            }

            string fileName    = variables.Expand(cmd.Operands[0]);
            string rawFileName = cmd.Operands[0];

            bool     preserve = false;
            bool     noWarn   = false;
            Encoding encoding = null;

            for (int i = necessaryOperandNum; i < cmd.Operands.Length; i++)
            {
                string operand = cmd.Operands[i];
                switch (operand.ToUpper())
                {
                case "PRESERVE":
                    preserve = true;
                    break;

                case "NOWARN":
                    noWarn = true;
                    break;

                case "UTF8":
                    if (encoding == null)
                    {
                        encoding = Encoding.UTF8;
                    }
                    else
                    {
                        throw new InvalidOperandException("Encoding operand only can be used once");
                    }
                    break;

                case "UTF16":
                    if (encoding == null)
                    {
                        encoding = Encoding.Unicode;
                    }
                    else
                    {
                        throw new InvalidOperandException("Encoding operand only can be used once");
                    }
                    break;

                case "UTF16LE":
                    if (encoding == null)
                    {
                        encoding = Encoding.Unicode;
                    }
                    else
                    {
                        throw new InvalidOperandException("Encoding operand only can be used once");
                    }
                    break;

                case "UTF16BE":
                    if (encoding == null)
                    {
                        encoding = Encoding.BigEndianUnicode;
                    }
                    else
                    {
                        throw new InvalidOperandException("Encoding operand only can be used once");
                    }
                    break;

                case "ANSI":
                    if (encoding == null)
                    {
                        encoding = Encoding.Default;
                    }
                    else
                    {
                        throw new InvalidOperandException("Encoding operand only can be used once");
                    }
                    break;

                default:
                    throw new InvalidOperandException(string.Concat("Invalid operand ", operand), cmd);
                }
            }

            // Default Encoding - UTF8
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            // If file already exists,
            if (File.Exists(fileName))
            {
                if (!preserve)
                {
                    logs.Add(new LogInfo(cmd, string.Concat("\'", rawFileName, "\' will be overwritten"), noWarn ? LogState.Ignore : LogState.Warning));
                }
            }

            try
            {
                FileStream fs = new FileStream(fileName, preserve ? FileMode.CreateNew : FileMode.Create, FileAccess.Write, FileShare.Write);
                Helper.WriteTextBOM(fs, encoding).Close();
                logs.Add(new LogInfo(cmd, string.Concat("Created blank text file \'", rawFileName, "\'"), LogState.Success));
            }
            catch (IOException)
            {
                if (preserve)
                {
                    logs.Add(new LogInfo(cmd, string.Concat("Cannot overwrite \'", rawFileName, "\'"), noWarn ? LogState.Ignore : LogState.Warning));
                }
            }

            return(logs.ToArray(typeof(LogInfo)) as LogInfo[]);
        }
示例#15
0
 public PathNotDirException(BakeryCommand command)
 {
 }
示例#16
0
 public PathNotFileException(BakeryCommand command)
 {
 }
示例#17
0
        /// <summary>
        /// FileRename,<srcFileName>,<destFileName>
        /// Wildcard not supported
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public LogInfo[] FileMove(BakeryCommand cmd)
        {
            ArrayList logs = new ArrayList();

            // Necessary operand : 2, optional operand : 0
            const int necessaryOperandNum = 2;
            const int optionalOperandNum  = 0;

            if (cmd.Operands.Length < necessaryOperandNum)
            {
                throw new InvalidOperandException("Necessary operands does not exist", cmd);
            }
            else if (necessaryOperandNum + optionalOperandNum < cmd.Operands.Length)
            {
                throw new InvalidOperandException("Too many operands", cmd);
            }

            string srcFileName     = variables.Expand(cmd.Operands[0]);
            string rawSrcFileName  = cmd.Operands[0];
            string destFileName    = variables.Expand(cmd.Operands[1]);
            string rawDestFileName = cmd.Operands[1];

            // Check if srcFileName exists
            if (File.Exists(srcFileName) == false)
            {
                throw new FileNotFoundException(string.Concat("\'", rawSrcFileName, "\' does not exist"));
            }

            // src and dest filename is same, so log it
            if (string.Equals(Helper.RemoveLastDirChar(srcFileName), Helper.RemoveLastDirChar(destFileName), StringComparison.OrdinalIgnoreCase))
            {
                logs.Add(new LogInfo(cmd, string.Concat("Cannot rename to same filename"), LogState.Warning));
            }
            else
            {
                // File.Move cannot move file if volume is different.
                string srcFileDrive  = Path.GetPathRoot(Path.GetFullPath(srcFileName));
                string destFileDrive = Path.GetPathRoot(Path.GetFullPath(destFileName));
                if (string.Equals(srcFileDrive, destFileDrive, StringComparison.OrdinalIgnoreCase))
                { // Same volume. Just use File.Move.
                    File.Move(srcFileName, destFileName);
                    logs.Add(new LogInfo(cmd, string.Concat("\'", rawSrcFileName, "\' moved to \'", rawDestFileName, "\'"), LogState.Success));
                }
                else
                { // Use File.Copy and File.Delete instead.
                    try
                    {
                        File.Copy(srcFileName, destFileName, false);
                        File.Delete(srcFileName);
                        logs.Add(new LogInfo(cmd, string.Concat("\'", rawSrcFileName, "\' moved to \'", rawDestFileName, "\'"), LogState.Success));
                    }
                    catch (IOException)
                    {
                        logs.Add(new LogInfo(cmd, string.Concat("Cannot overwrite \'", rawDestFileName, "\'"), LogState.Warning));
                    }
                }
            }


            return(logs.ToArray(typeof(LogInfo)) as LogInfo[]);
        }
示例#18
0
        /// <summary>
        /// FileDelete,<FileName>,[,NOWARN][,NOREC]
        /// Wildcard supported in <FileName>
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public LogInfo[] FileDelete(BakeryCommand cmd)
        {
            ArrayList logs = new ArrayList();

            // Necessary operand : 1, optional operand : 2
            const int necessaryOperandNum = 1;
            const int optionalOperandNum  = 2;

            if (cmd.Operands.Length < necessaryOperandNum)
            {
                throw new InvalidOperandException("Necessary operands does not exist", cmd);
            }
            else if (necessaryOperandNum + optionalOperandNum < cmd.Operands.Length)
            {
                throw new InvalidOperandException("Too many operands", cmd);
            }

            string filePath    = variables.Expand(cmd.Operands[0]);
            string rawFilePath = cmd.Operands[0];

            // Check srcFileName contains wildcard
            bool filePathContainsWildcard = true;

            if (filePath.IndexOfAny(new char[] { '*', '?' }) == -1) // No wildcard
            {
                filePathContainsWildcard = false;
            }
            // Check destPath is directory
            if (Directory.Exists(filePath))
            {
                throw new PathNotFileException(string.Concat(filePath, " cannot be directory"), cmd);
            }

            bool noWarn = false;
            bool noRec  = false;

            for (int i = necessaryOperandNum; i < cmd.Operands.Length; i++)
            {
                string operand = cmd.Operands[i];
                switch (operand.ToUpper())
                {
                case "NOWARN":     // no warning when if the file does not exists
                    noWarn = true;
                    break;

                case "NOREC":     // no recursive wildcard copy
                    noRec = true;
                    break;

                default:
                    throw new InvalidOperandException(string.Concat("Invalid operand ", operand), cmd);
                }
            }

            try
            {
                if (filePathContainsWildcard) // wildcard exists
                {
                    string   srcDirToFind    = Helper.GetDirNameEx(filePath);
                    string   rawSrcDirToFind = Helper.GetDirNameEx(rawFilePath);
                    string[] listToDelete;
                    if (noRec)
                    {
                        listToDelete = Directory.GetFiles(srcDirToFind, Path.GetFileName(filePath));
                    }
                    else
                    {
                        listToDelete = Directory.GetFiles(srcDirToFind, Path.GetFileName(filePath), SearchOption.AllDirectories);
                    }
                    foreach (string searchedFilePath in listToDelete)
                    {
                        File.Delete(searchedFilePath);
                        string searchedFileName = searchedFilePath.Remove(0, srcDirToFind.Length + 1); // 1 for \\
                        logs.Add(new LogInfo(cmd, string.Concat(@"'", Path.Combine(rawSrcDirToFind, searchedFileName), @"' deleted"), LogState.Success));
                    }
                    if (listToDelete.Length == 0)
                    {
                        if (!noWarn) // file is not found
                        {
                            logs.Add(new LogInfo(cmd, string.Concat(@"'", rawFilePath, @"' not found"), LogState.Warning));
                        }
                    }
                }
                else // No wildcard
                {
                    if (!noWarn && !File.Exists(filePath)) // File.Delete does not throw exception when file is not found
                    {
                        logs.Add(new LogInfo(cmd, string.Concat(@"'", rawFilePath, @"' not found"), LogState.Warning));
                    }
                    File.Delete(filePath);
                    logs.Add(new LogInfo(cmd, string.Concat(@"'", rawFilePath, @"' deleted"), LogState.Success));
                }
            }
            catch (Exception e)
            {
                logs.Add(new LogInfo(cmd, string.Concat(e.GetType(), ": ", e.Message), LogState.Error));
            }

            return(logs.ToArray(typeof(LogInfo)) as LogInfo[]);
        }
示例#19
0
 public InvalidOpcodeException(BakeryCommand command)
 {
 }
示例#20
0
 public InvalidOperandException(BakeryCommand command)
 {
 }
示例#21
0
        /*
         * Text Manipulation
         */

        /// <summary>
        /// TXTAddLine,<FileName>,<Line>,<Mode>
        /// Mode : Prepend / Append / Place,LineNum
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public LogInfo[] TXTAddLine(BakeryCommand cmd)
        {
            ArrayList logs = new ArrayList();

            // Necessary operand : 3, optional operand : 1
            const int necessaryOperandNum = 3;
            const int optionalOperandNum  = 1;

            if (cmd.Operands.Length < necessaryOperandNum)
            {
                throw new InvalidOperandException("Necessary operands does not exist", cmd);
            }
            else if (necessaryOperandNum + optionalOperandNum < cmd.Operands.Length)
            {
                throw new InvalidOperandException("Too many operands", cmd);
            }

            // Get operands
            string fileName     = variables.Expand(cmd.Operands[0]);
            string rawFileName  = cmd.Operands[0];
            string line         = variables.Expand(cmd.Operands[1]);
            int    mode         = 1;
            int    placeLineNum = 0;

            if (string.Equals(cmd.Operands[2], "Prepend", StringComparison.OrdinalIgnoreCase))
            {
                mode = 0;
                if (4 <= cmd.Operands.Length)
                {
                    throw new InvalidOperandException("Too many operands");
                }
            }
            else if (string.Equals(cmd.Operands[2], "Append", StringComparison.OrdinalIgnoreCase))
            {
                mode = 1;
                if (4 <= cmd.Operands.Length)
                {
                    throw new InvalidOperandException("Too many operands");
                }
            }
            else if (string.Equals(cmd.Operands[2], "Place", StringComparison.OrdinalIgnoreCase))
            {
                mode = 2;
                if (5 <= cmd.Operands.Length)
                {
                    throw new InvalidOperandException("Too many operands");
                }
                else if (cmd.Operands.Length == 3)
                {
                    throw new InvalidOperandException("Not enough operands");
                }
                placeLineNum = int.Parse(cmd.Operands[3]);
                if (placeLineNum <= 0) // In Place mode, placeLineNum starts from 1;
                {
                    throw new InvalidOperandException("Invalid LineNum value. LineNum starts from 1.");
                }
            }
            else
            {
                throw new InvalidOperandException("Invalid mode of TXTADDLine");
            }

            // Detect encoding of text
            // If text does not exists, create blank file
            Encoding encoding = Encoding.UTF8;

            if (File.Exists(fileName))
            {
                encoding = Helper.DetectTextEncoding(fileName);
            }
            else
            {
                Helper.WriteTextBOM(new FileStream(fileName, FileMode.Create, FileAccess.Write), Encoding.UTF8);
            }

            if (mode == 0) // Prepend
            {
                string       rawText = Helper.ReadTextFile(fileName);
                StreamWriter sw      = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write), encoding);
                sw.WriteLine(line);
                sw.Write(rawText);
                sw.Close();
                logs.Add(new LogInfo(cmd, string.Concat("Prepened '", line, "' to '", rawFileName, "'"), LogState.Success));
            }
            else if (mode == 1) // Append
            {
                File.AppendAllText(fileName, line + "\r\n", encoding);
                logs.Add(new LogInfo(cmd, string.Concat("Appended '", line, "' to '", rawFileName, "'"), LogState.Success));
            }
            else if (mode == 2) // Place
            {                   // In Place mode, placeLineNum starts from 1;
                int    count   = 1;
                int    offset  = 0;
                string rawText = Helper.ReadTextFile(fileName);
                // Get offset of start of (placeLineNum)'th line
                while ((count < placeLineNum) && (offset = rawText.IndexOf("\r\n", offset)) != -1)
                {
                    offset += 2;
                    count++;
                }
                if (offset == -1) // placeLineNum is bigger than text file's line num, so works as 'Append'
                {
                    offset = rawText.Length;
                }
                // Write to file
                StreamWriter sw = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write), encoding);
                sw.Write(rawText.Substring(0, offset));
                sw.WriteLine(line);
                sw.Write(rawText.Substring(offset));
                sw.Close();
                logs.Add(new LogInfo(cmd, string.Concat("Placed '", line, "' to '", rawFileName, "'"), LogState.Success));
            }

            return(logs.ToArray(typeof(LogInfo)) as LogInfo[]);
        }
示例#22
0
 public InvalidOperandException(string message, BakeryCommand command) : base(message)
 {
     this.command = command;
 }
示例#23
0
        public LogInfo[] AddVariables(BakeryCommand cmd)
        {
            ArrayList logs = new ArrayList();

            // Necessary operand : 2, optional operand : 1
            const int necessaryOperandNum = 2;
            const int optionalOperandNum  = 1;

            if (cmd.Operands.Length < necessaryOperandNum)
            {
                throw new InvalidOperandException("Necessary operands does not exist", cmd);
            }
            else if (necessaryOperandNum + optionalOperandNum < cmd.Operands.Length)
            {
                throw new InvalidOperandException("Too many operands", cmd);
            }

            string varKey;
            string varValue;
            bool   global    = false;
            bool   permanent = false;

            // Get optional operand
            if (cmd.Operands.Length == 3)
            {
                switch (cmd.Operands[2].ToUpper())
                {
                case "GLOBAL":
                    global = true;
                    break;

                case "PERMANENT":
                    permanent = true;
                    break;

                default:
                    throw new InvalidOperandException("Invalid operand : " + cmd.Operands[2]);
                }
            }

            varKey   = cmd.Operands[0].Trim(new char[] { '%' });
            varValue = cmd.Operands[1];

            bool isVarCreated = false;

            if (global || permanent)
            {
                isVarCreated = variables.GlobalContainsKey(varKey);
                variables.GlobalSetValue(varKey, varValue);
            }
            else
            {
                isVarCreated = variables.LocalContainsKey(varKey);
                variables.LocalSetValue(varKey, varValue);
            }

            if (isVarCreated)
            {
                logs.Add(new LogInfo(cmd, string.Concat("Var %", varKey, "% set to ", varValue), LogState.Success));
            }
            else
            {
                logs.Add(new LogInfo(cmd, string.Concat("Var %", varKey, "% created, set to ", varValue), LogState.Success));
            }

            return(logs.ToArray(typeof(LogInfo)) as LogInfo[]);
        }
示例#24
0
        /// <summary>
        /// Execute one command.
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="logger"></param>
        private void ExecuteCommand(BakeryCommand cmd, Logger logger)
        {
            LogInfo log = null;

            LogInfo[] logs = null;

            DisplayOperation(cmd);
            try
            {
                switch (cmd.Opcode)
                {
                // File
                case Opcode.FileCopy:
                    logs = this.FileCopy(cmd);
                    break;

                case Opcode.FileDelete:
                    logs = this.FileDelete(cmd);
                    break;

                case Opcode.FileRename:
                case Opcode.FileMove:
                    logs = this.FileMove(cmd);
                    break;

                case Opcode.FileCreateBlank:
                    logs = this.FileCreateBlank(cmd);
                    break;

                // Registry
                // Text
                case Opcode.TXTAddLine:
                    logs = this.TXTAddLine(cmd);
                    break;

                // INI
                // Network
                // Attach
                // UI
                // StringFormat
                // System
                // Branch
                case Opcode.Run:
                case Opcode.Exec:
                    logs = this.RunExec(cmd);
                    break;

                // Control
                case Opcode.Set:
                    logs = this.Set(cmd);
                    break;

                case Opcode.None:
                    log = new LogInfo(cmd, "NOP", LogState.None);
                    break;

                case Opcode.Comment:
                    log = new LogInfo(cmd, "Comment", LogState.Ignore);
                    break;

                default:
                    throw new InvalidOpcodeException("Cannot execute \'" + cmd.Opcode.ToString() + "\' command", cmd);
                }
            }
            catch (Exception e)
            {
                logger.Write(new LogInfo(cmd, string.Concat(e.GetType(), ": ", Helper.RemoveLastNewLine(e.Message)), LogState.Error));
            }


            if (log != null)
            {
                logger.Write(log);
            }
            if (logs != null)
            {
                logger.Write(logs);
            }
        }