コード例 #1
0
ファイル: Program.cs プロジェクト: 751620780/Peach
        public Program(string[] args)
        {
            AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload);
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            config       = new RunConfiguration();
            config.debug = 0;

            try
            {
                string analyzer      = null;
                bool   test          = false;
                string agent         = null;
                var    definedValues = new List <string>();
                bool   parseOnly     = false;

                var color = Console.ForegroundColor;
                Console.Write("\n");
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("[[ ");
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine(ProductName);
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("[[ ");
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine(Copyright);
                Console.ForegroundColor = color;

                if (args.Length == 0)
                {
                    Syntax();
                }

                var p = new OptionSet()
                {
                    { "h|?|help", v => Syntax() },
                    { "analyzer=", v => analyzer = v },
                    { "debug", v => config.debug = 1 },
                    { "trace", v => config.debug = 2 },
                    { "1", v => config.singleIteration = true },
                    { "range=", v => ParseRange(config, v) },
                    { "t|test", v => test = true },
                    { "c|count", v => config.countOnly = true },
                    { "skipto=", v => config.skipToIteration = Convert.ToUInt32(v) },
                    { "seed=", v => config.randomSeed = Convert.ToUInt32(v) },
                    { "p|parallel=", v => ParseParallel(config, v) },
                    { "a|agent=", v => agent = v },
                    { "D|define=", v => AddNewDefine(v) },
                    { "definedvalues=", v => definedValues.Add(v) },
                    { "config=", v => definedValues.Add(v) },
                    { "parseonly", v => parseOnly = true },
                    { "bob", var => bob() },                    //输出他的头像,醉了
                    { "charlie", var => Charlie() },            //醉了
                    { "showdevices", var => ShowDevices() },    //列出网卡设备信息
                    { "showenv", var => ShowEnvironment() },    //输出使用信息?基本属性的使用?
                    { "makexsd", var => MakeSchema() },         //生成Peach.xsd文件
                };

                List <string> extra = p.Parse(args);//extra[0]存放文件名即 pit文件.xml

                if (extra.Count == 0 && agent == null && analyzer == null)
                {
                    Syntax();
                }

                Platform.LoadAssembly();

                AddNewDefine("Peach.Cwd=" + Environment.CurrentDirectory);
                AddNewDefine("Peach.Pwd=" + Path.GetDirectoryName(Assembly.GetCallingAssembly().Location));

                // 判断是否有 pit文件.xml.config 文件,如果有我们就加载改文件
                // 注意:pit文件.xml.config 应该和 pit文件.xml文件放在同一目录下
                if (extra.Count > 0 && File.Exists(extra[0]) &&
                    extra[0].ToLower().EndsWith(".xml") &&
                    File.Exists(extra[0] + ".config"))
                {
                    definedValues.Insert(0, extra[0] + ".config");
                }

                foreach (var definedValuesFile in definedValues)
                {
                    var defs = PitParser.parseDefines(definedValuesFile);

                    foreach (var kv in defs)
                    {
                        // Allow command line to override values in XML file.
                        if (!DefinedValues.ContainsKey(kv.Key))
                        {
                            DefinedValues.Add(kv.Key, kv.Value);
                        }
                    }
                }

                // 如果需要则启动调试
                // 如果已经由.congig文件进行配置,则不会做任何更改
                ConfigureLogging(config.debug);

                if (agent != null)
                {
                    var agentType = ClassLoader.FindTypeByAttribute <AgentServerAttribute>((x, y) => y.name == agent);
                    if (agentType == null)
                    {
                        Console.WriteLine("错误, unable to locate agent server for protocol '" + agent + "'.\n");
                        return;
                    }

                    var agentServer = Activator.CreateInstance(agentType) as IAgentServer;

                    ConsoleWatcher.WriteInfoMark();
                    Console.WriteLine("启动代理服务...");

                    agentServer.Run(new Dictionary <string, string>());
                    return;
                }

                if (analyzer != null)
                {
                    var analyzerType = ClassLoader.FindTypeByAttribute <AnalyzerAttribute>((x, y) => y.Name == analyzer);
                    if (analyzerType == null)
                    {
                        Console.WriteLine("错误,无法定位名为'" + analyzer + "'的analyzer.\n");
                        return;
                    }

                    var field = analyzerType.GetField("supportCommandLine",
                                                      BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
                    if ((bool)field.GetValue(null) == false)
                    {
                        Console.WriteLine("错误, 从命令行启动的analyzer还没有进行配置.");
                        return;
                    }

                    var analyzerInstance = Activator.CreateInstance(analyzerType) as Analyzer;

                    ConsoleWatcher.WriteInfoMark();
                    Console.WriteLine("启动Analyzer...");

                    analyzerInstance.asCommandLine(new Dictionary <string, string>());
                    return;
                }

                Dictionary <string, object> parserArgs = new Dictionary <string, object>();
                parserArgs[PitParser.DEFINED_VALUES] = this.DefinedValues;

                if (test)
                {
                    ConsoleWatcher.WriteInfoMark();
                    Console.Write("Validating file [" + extra[0] + "]... ");
                    Analyzer.defaultParser.asParserValidation(parserArgs, extra[0]);

                    if (Type.GetType("Mono.Runtime") != null)
                    {
                        Console.WriteLine("File parsed successfully, but XSD validation is not supported on the Mono runtime.");
                    }
                    else
                    {
                        Console.WriteLine("No Errors Found.");
                    }

                    return;
                }

                Engine e = new Engine(GetUIWatcher());
                dom            = GetParser(e).asParser(parserArgs, extra[0]);
                config.pitFile = extra[0];

                // 用于单元测试
                if (parseOnly)
                {
                    return;
                }

                foreach (string arg in args)
                {
                    config.commandLine += arg + " ";
                }

                if (extra.Count > 1)
                {
                    config.runName = extra[1];
                }

                e.startFuzzing(dom, config);

                exitCode = 0;
            }
            catch (SyntaxException)
            {
                // 由syntax()抛出,可忽略
            }
            catch (OptionException oe)
            {
                Console.WriteLine(oe.Message + "\n");
            }
            catch (PeachException ee)
            {
                if (config.debug > 0)
                {
                    Console.WriteLine(ee);
                }
                else
                {
                    Console.WriteLine(ee.Message + "\n");
                }
            }
            finally
            {
                // HACK - 需使用NLog 2.0的Mono
                ConfigureLogging(-1);

                // 重置控制台输出文字的颜色
                Console.ForegroundColor = DefaultForground;
            }
        }
コード例 #2
0
        public Program(string[] args)
        {
            AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload);
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            RunConfiguration config = new RunConfiguration();

            config.debug = false;

            try
            {
                string analyzer      = null;
                bool   test          = false;
                string agent         = null;
                var    definedValues = new List <string>();
                bool   parseOnly     = false;

                var color = Console.ForegroundColor;
                Console.Write("\n");
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("[[ ");
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine(ProductName);
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("[[ ");
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine(Copyright);
                Console.WriteLine();
                Console.ForegroundColor = color;

                if (args.Length == 0)
                {
                    Syntax();
                }

                var p = new OptionSet()
                {
                    { "h|?|help", v => Syntax() },
                    { "analyzer=", v => analyzer = v },
                    { "debug", v => config.debug = true },
                    { "1", v => config.singleIteration = true },
                    { "range=", v => ParseRange(config, v) },
                    { "t|test", v => test = true },
                    { "c|count", v => config.countOnly = true },
                    { "skipto=", v => config.skipToIteration = Convert.ToUInt32(v) },
                    { "seed=", v => config.randomSeed = Convert.ToUInt32(v) },
                    { "p|parallel=", v => ParseParallel(config, v) },
                    { "a|agent=", v => agent = v },
                    { "D|define=", v => AddNewDefine(v) },
                    { "definedvalues=", v => definedValues.Add(v) },
                    { "parseonly", v => parseOnly = true },
                    { "bob", var => bob() },
                    { "charlie", var => Charlie() },
                    { "showdevices", var => ShowDevices() },
                    { "showenv", var => ShowEnvironment() },
                    { "inputFilePath=", v => config.inputFilePath = v },
                    { "outputFilePath=", v => config.outputFilePath = v },
                };

                List <string> extra = p.Parse(args);

                if (extra.Count == 0 && agent == null && analyzer == null)
                {
                    Syntax();
                }

                Platform.LoadAssembly();

                AddNewDefine("Peach.Cwd=" + Environment.CurrentDirectory);

                foreach (var definedValuesFile in definedValues)
                {
                    var defs = PitParser.parseDefines(definedValuesFile);

                    foreach (var kv in defs)
                    {
                        // Allow command line to override values in XML file.
                        if (!DefinedValues.ContainsKey(kv.Key))
                        {
                            DefinedValues.Add(kv.Key, kv.Value);
                        }
                    }
                }

                // Enable debugging if asked for
                if (config.debug)
                {
                    var nconfig       = new LoggingConfiguration();
                    var consoleTarget = new ColoredConsoleTarget();
                    nconfig.AddTarget("console", consoleTarget);
                    consoleTarget.Layout = "${logger} ${message}";

                    var rule = new LoggingRule("*", LogLevel.Debug, consoleTarget);
                    nconfig.LoggingRules.Add(rule);

                    LogManager.Configuration = nconfig;
                }

                if (agent != null)
                {
                    var agentType = ClassLoader.FindTypeByAttribute <AgentServerAttribute>((x, y) => y.name == agent);
                    if (agentType == null)
                    {
                        Console.WriteLine("Error, unable to locate agent server for protocol '" + agent + "'.\n");
                        return;
                    }

                    var agentServer = Activator.CreateInstance(agentType) as IAgentServer;

                    ConsoleWatcher.WriteInfoMark();
                    Console.WriteLine("Starting agent server");

                    agentServer.Run(new Dictionary <string, string>());
                    return;
                }

                if (analyzer != null)
                {
                    var analyzerType = ClassLoader.FindTypeByAttribute <AnalyzerAttribute>((x, y) => y.Name == analyzer);
                    if (analyzerType == null)
                    {
                        Console.WriteLine("Error, unable to locate analyzer called '" + analyzer + "'.\n");
                        return;
                    }

                    var field = analyzerType.GetField("supportCommandLine",
                                                      BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
                    if ((bool)field.GetValue(null) == false)
                    {
                        Console.WriteLine("Error, analyzer not configured to run from command line.");
                        return;
                    }

                    var analyzerInstance = Activator.CreateInstance(analyzerType) as Analyzer;

                    ConsoleWatcher.WriteInfoMark();
                    Console.WriteLine("Starting Analyzer");

                    analyzerInstance.asCommandLine(new Dictionary <string, string>());
                    return;
                }

                Dictionary <string, object> parserArgs = new Dictionary <string, object>();
                parserArgs[PitParser.DEFINED_VALUES] = this.DefinedValues;

                if (test)
                {
                    ConsoleWatcher.WriteInfoMark();
                    Console.Write("Validating file [" + extra[0] + "]... ");
                    Analyzer.defaultParser.asParserValidation(parserArgs, extra[0]);

                    if (Type.GetType("Mono.Runtime") != null)
                    {
                        Console.WriteLine("File parsed successfully, but XSD validation is not supported on the Mono runtime.");
                    }
                    else
                    {
                        Console.WriteLine("No Errors Found.");
                    }

                    return;
                }

                Engine e = new Engine(GetUIWatcher());
                dom            = GetParser(e).asParser(parserArgs, extra[0]);
                config.pitFile = extra[0];

                // Used for unittests
                if (parseOnly)
                {
                    return;
                }

                foreach (string arg in args)
                {
                    config.commandLine += arg + " ";
                }

                if (extra.Count > 1)
                {
                    if (!dom.tests.ContainsKey(extra[1]))
                    {
                        throw new PeachException("Error, unable to locate test named \"" + extra[1] + "\".");
                    }

                    e.startFuzzing(dom, dom.tests[extra[1]], config);
                }
                else
                {
                    e.startFuzzing(dom, config);
                }

                exitCode = 0;
            }
            catch (SyntaxException)
            {
                // Ignore, thrown by syntax()
            }
            catch (OptionException oe)
            {
                Console.WriteLine(oe.Message + "\n");
            }
            catch (PeachException ee)
            {
                if (config.debug)
                {
                    Console.WriteLine(ee);
                }
                else
                {
                    Console.WriteLine(ee.Message + "\n");
                }
            }
            finally
            {
                // HACK - Required on Mono with NLog 2.0
                LogManager.Configuration = null;

                // Reset console colors
                Console.ForegroundColor = DefaultForground;
            }
        }