public SMTLibProcess(ProcessStartInfo psi, SMTLibProverOptions options) { this.options = options; this.smtProcessId = smtProcessIdSeq++; if (options.Inspector != null) { this.inspector = new Inspector(options); } foreach (var arg in options.SolverArguments) psi.Arguments += " " + arg; if (cancelEvent == null && CommandLineOptions.Clo.RunningBoogieFromCommandLine) { cancelEvent = new ConsoleCancelEventHandler(ControlCHandler); Console.CancelKeyPress += cancelEvent; } if (options.Verbosity >= 1) { Console.WriteLine("[SMT-{0}] Starting {1} {2}", smtProcessId, psi.FileName, psi.Arguments); } try { prover = new Process(); prover.StartInfo = psi; prover.ErrorDataReceived += prover_ErrorDataReceived; prover.OutputDataReceived += prover_OutputDataReceived; prover.Start(); toProver = prover.StandardInput; prover.BeginErrorReadLine(); prover.BeginOutputReadLine(); } catch (System.ComponentModel.Win32Exception e) { throw new ProverException(string.Format("Unable to start the process {0}: {1}", psi.FileName, e.Message)); } }
public static void CanAddAndRemoveHandler() { ConsoleCancelEventHandler handler = new ConsoleCancelEventHandler(Console_CancelKeyPress); Console.CancelKeyPress += handler; Console.CancelKeyPress -= handler; }
public BasicConsole(bool colorful) { _output = System.Console.Out; _errorOutput = System.Console.Error; SetupColors(colorful); _creatingThread = Thread.CurrentThread; #if !SILVERLIGHT // ConsoleCancelEventHandler // Create the default handler this.ConsoleCancelEventHandler = delegate(object sender, ConsoleCancelEventArgs e) { if (e.SpecialKey == ConsoleSpecialKey.ControlC) { e.Cancel = true; _ctrlCEvent.Set(); _creatingThread.Abort(new KeyboardInterruptException("")); } }; Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { // Dispatch the registered handler ConsoleCancelEventHandler handler = this.ConsoleCancelEventHandler; if (handler != null) { this.ConsoleCancelEventHandler(sender, e); } }; #endif _ctrlCEvent = new AutoResetEvent(false); }
private void HandlerInvokedForSignal(int signalOuter, bool redirectStandardInput) { // On Windows we could use GenerateConsoleCtrlEvent to send a ctrl-C to the process, // however that'll apply to all processes associated with the same group, which will // include processes like the code coverage tool when doing code coverage runs, causing // those other processes to exit. As such, we test this only on Unix, where we can // send a SIGINT signal to this specific process only. // This test sends a SIGINT back to itself... if run in the xunit process, this would end // up canceling the rest of xunit's tests. So we run the test itself in a separate process. RemoteInvokeOptions options = new RemoteInvokeOptions(); options.StartInfo.RedirectStandardInput = redirectStandardInput; RemoteExecutor.Invoke(signalStr => { var tcs = new TaskCompletionSource <ConsoleSpecialKey>(); ConsoleCancelEventHandler handler = (sender, e) => { e.Cancel = true; tcs.SetResult(e.SpecialKey); }; Console.CancelKeyPress += handler; try { int signalInner = int.Parse(signalStr); Assert.Equal(0, kill(Environment.ProcessId, signalInner)); Assert.True(tcs.Task.Wait(WaitFailTestTimeoutSeconds * 1000)); Assert.Equal( signalInner == SIGINT ? ConsoleSpecialKey.ControlC : ConsoleSpecialKey.ControlBreak, tcs.Task.Result); } finally { Console.CancelKeyPress -= handler; } }, signalOuter.ToString(), options).Dispose(); }
internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey) { // The thread that this gets called back on has a very small stack on some systems. There is // not enough space to handle a managed exception being caught and thrown. So, run a task // on the threadpool for the actual event callback. // To avoid the race condition between remove handler and raising the event ConsoleCancelEventHandler cancelCallbacks = Console._cancelCallbacks; if (cancelCallbacks == null) { return(false); } var delegateData = new ControlCDelegateData(controlKey, cancelCallbacks); Task callBackTask = Task.Factory.StartNew( d => ((ControlCDelegateData)d).HandleBreakEvent(), delegateData, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); // Block until the delegate is done. We need to be robust in the face of the task not executing // but we also want to get control back immediately after it is done and we don't want to give the // handler a fixed time limit in case it needs to display UI. Wait on the task twice, once with a // timeout and a second time without if we are sure that the handler actually started. TimeSpan controlCWaitTime = new TimeSpan(0, 0, 30); // 30 seconds callBackTask.Wait(controlCWaitTime); if (!delegateData.DelegateStarted) { Debug.Assert(false, "The task to execute the handler did not start within 30 seconds."); return(false); } callBackTask.Wait(); return(delegateData.Cancel); }
internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey) { // The thread that this gets called back on has a very small stack on some systems. There is // not enough space to handle a managed exception being caught and thrown. So, queue up a work // item on another thread for the actual event callback. // To avoid the race condition between remove handler and raising the event ConsoleCancelEventHandler cancelCallbacks = Console._cancelCallbacks; if (cancelCallbacks == null) { return(false); } // Create the delegate ControlCDelegateData delegateData = new ControlCDelegateData(controlKey, cancelCallbacks); WaitCallback controlCCallback = new WaitCallback(ControlCDelegate); // Queue the delegate ThreadPool.QueueUserWorkItem(controlCCallback, delegateData); // Block until the delegate is done. We need to be robust in the face of the work item not executing // but we also want to get control back immediately after it is done and we don't want to give the // handler a fixed time limit in case it needs to display UI. Wait on the event twice, once with a // timout and a second time without if we are sure that the handler actually started. TimeSpan controlCWaitTime = new TimeSpan(0, 0, 30); // 30 seconds delegateData.CompletionEvent.WaitOne(controlCWaitTime); if (!delegateData.DelegateStarted) { Debug.Assert(false, "ThreadPool.QueueUserWorkItem did not execute the handler within 30 seconds."); return(false); } delegateData.CompletionEvent.WaitOne(); delegateData.CompletionEvent.Dispose(); return(delegateData.Cancel); }
public static void Main(string[] args) { var connectionString = args[0]; var driverWorkload = BsonDocument.Parse(args[1]); var cancellationTokenSource = new CancellationTokenSource(); ConsoleCancelEventHandler cancelHandler = (o, e) => HandleCancel(e, cancellationTokenSource); var resultsDir = Environment.GetEnvironmentVariable("RESULTS_DIR"); var resultsPath = resultsDir == null ? "results.json" : Path.Combine(resultsDir, "results.json"); Console.WriteLine($"dotnet main> Results will be written to {resultsPath}..."); try { Console.CancelKeyPress += cancelHandler; Console.WriteLine("dotnet main> Starting workload executor..."); if (!bool.TryParse(Environment.GetEnvironmentVariable("ASYNC"), out bool async)) { async = true; } ExecuteWorkload(connectionString, driverWorkload, async, cancellationTokenSource.Token); } finally { Console.CancelKeyPress -= cancelHandler; Console.WriteLine("dotnet main finally> Writing final results file"); var resultsJson = ConvertResultsToJson(); Console.WriteLine(resultsJson); #if NETCOREAPP2_1 File.WriteAllTextAsync(resultsPath, resultsJson).Wait(); #else File.WriteAllText(resultsPath, resultsJson); #endif } }
public SimpleConsoleService(Action startAction = null, Action <CancellationToken> workAction = null, Action stopAction = null) { quitEvent = new ManualResetEventSlim(); cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; quitThread = new Thread(() => { while (!quitEvent.Wait(FromSeconds(10))) { Console.WriteLine($"{quitText}"); } ; }); ConsoleCancelEventHandler cancelKeyPressHandler = (o, a) => { a.Cancel = true; cancellationTokenSource.Cancel(); quitEvent.Set(); }; startAction?.Invoke(); Console.WriteLine($"Server started. {quitText}"); Console.CancelKeyPress += cancelKeyPressHandler; quitThread.Start(); workAction?.Invoke(cancellationToken); quitThread.Join(); Console.CancelKeyPress -= cancelKeyPressHandler; stopAction?.Invoke(); Console.WriteLine("Server stopped."); }
/// <summary> /// This implementation allows one to call this function multiple times during the /// execution of a console application. The CtrlC handling is disabled when Ctrl-C /// is typed, one will need to call this method again to re-enable it. /// </summary> /// <param name="action"></param> private static void SetupCtrlCHandler(Action action) { ctrlCExecuted = false; // uninstall previous handler if (ctrlCHandler != null) { Console.CancelKeyPress -= ctrlCHandler; } ctrlCHandler = (object sender, ConsoleCancelEventArgs cancelArgs) => { if (!ctrlCExecuted) { ctrlCExecuted = true; Console.WriteLine("Stopping monitor"); action(); cancelArgs.Cancel = true; } }; Console.CancelKeyPress += ctrlCHandler; }
protected EventComponent(IOutput output, params string[] queries) { _running = true; _output = output; _queries = queries; _eventStream = null; _eventProcessor = null; _outputSubscription = null; _intermediateSubscription = null; // Setting up clean-up code for exit _cancelEventHandler = delegate(object sender, ConsoleCancelEventArgs eventArgs) { if (_running) { Stop(); } else { Console.CancelKeyPress -= _cancelEventHandler; } }; Console.CancelKeyPress += _cancelEventHandler; }
static void Main(string[] args) { Executable = new FileInfo(Environment.GetCommandLineArgs()[0]); Terminal.Setup(); Commands.Load(); ConsoleCancelEventHandler BlockCtrlC = delegate(object o, ConsoleCancelEventArgs e) { if (Current != null && Current.IsAlive) { Current.Abort(); } e.Cancel = true; CurrentParser.Exit = true; }; Console.CancelKeyPress += BlockCtrlC; while (true) { Terminal.ResetColors(); string Input = Terminal.PrettyInput(); bool Ran = false; while (!Ran) { if (Input == null) { Input = Terminal.ReadLine(); continue; } if (Input != string.Empty) { RunCommand(Input); } Ran = true; } } }
static int Main(string[] args) { try { using (var prog = new Program(vkToken: args[0], aiToken: args[1], lang: SupportedLanguage.Russian)) { var cts = new CancellationTokenSource(); var handler = new ConsoleCancelEventHandler((sender, evargs) => { cts.Cancel(); evargs.Cancel = true; }); Console.CancelKeyPress += handler; try { prog.RunAsync(cts.Token).GetAwaiter().GetResult(); } finally { Console.CancelKeyPress -= handler; } } return(0); } catch (Exception e) { Console.Error.WriteLine("EXCEPTION: {0}", e); return(1); } }
public IDisposable Create(EventHandler processExitEventHandler, ConsoleCancelEventHandler cancelKeyPressEventHandler) { return(new ShutdownHandle(processExitEventHandler, cancelKeyPressEventHandler)); }
/// <summary> /// This implementation allows one to call this function multiple times during the /// execution of a console application. The CtrlC handling is disabled when Ctrl-C /// is typed, one will need to call this method again to re-enable it. /// </summary> /// <param name="action"></param> private static void SetupCtrlCHandler(Action action) { s_bCtrlCExecuted = false; // uninstall previous handler if (s_CtrlCHandler != null) Console.CancelKeyPress -= s_CtrlCHandler; s_CtrlCHandler = (object sender, ConsoleCancelEventArgs cancelArgs) => { if (!s_bCtrlCExecuted) { s_bCtrlCExecuted = true; // ensure not reentrant Out.WriteLine("Stopping monitor"); action(); // execute custom action // terminate normally (i.e. when the monitoring tasks complete b/c we've stopped the sessions) cancelArgs.Cancel = true; } }; Console.CancelKeyPress += s_CtrlCHandler; }
/// <summary> /// Calls the run command delegate and provides a method which developers can override when the command is ran. /// </summary> /// <param name="World"></param> /// <param name="args"></param> public virtual void Execute(World World, params string[] args) { if (NumRequiredArgs > 0 && (args == null || args.Length != NumRequiredArgs)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Required arguments(" + NumRequiredArgs + ") not present. For usage type \"help <command>\""); } else //Run the command { Thread execution = new Thread(new ThreadStart(() => { _Execute(World, args); })); execution.Start(); var quit = new ConsoleCancelEventHandler((s, a) => { a.Cancel = true; execution.Abort(); }); Console.CancelKeyPress += quit; while (execution.IsAlive) ; Console.WriteLine(); } }
internal ControlCDelegateData(ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks) { this.ControlKey = controlKey; this.CancelCallbacks = cancelCallbacks; this.CompletionEvent = new ManualResetEvent(false); // this.Cancel defaults to false // this.DelegateStarted defaults to false }
static void Main(string[] args) { var twiffer = new TwifferClient(); var accountNames = Settings.Default.SearchAccounts.ToArray(); var searchOpts = new SearchOptions() { Since = Settings.Default.SearchSince, Until = Settings.Default.SearchUntil, Accounts = accountNames }; var fileName = Settings.Default.OutputFileName; var progress = new Progress <int>(OnProgressUpdated); var cts = new CancellationTokenSource(); //var fileStream = File.CreateText(fileName); var fileStream = new StreamWriter( new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write), Encoding.UTF8); ThreadStart action = () => twiffer.ExportTweets(searchOpts, fileStream, progress, cts.Token); Thread work = new Thread(action); ConsoleCancelEventHandler consoleCancelHandler = null; Console.WriteLine("Search since: {0}", Settings.Default.SearchSince); Console.WriteLine("Search until: {0}", Settings.Default.SearchUntil); Console.WriteLine("Search in: {0}", string.Join(", ", accountNames)); Console.WriteLine("\nPress Enter to start or Esc to terminate."); var key = BlockTillKeyPress(ConsoleKey.Escape, ConsoleKey.Enter); if (key == ConsoleKey.Enter) { consoleCancelHandler = (o, e) => { e.Cancel = true; if (work.IsAlive) { cts.Cancel(); } fileStream.Dispose(); fileStream = File.CreateText(fileName); Console.WriteLine("\nCancelling..."); Console.CancelKeyPress -= consoleCancelHandler; }; Console.CancelKeyPress += consoleCancelHandler; Console.WriteLine("\nLoading..."); work.Start(); work.Join(); Console.WriteLine("\nPress Enter to quit."); BlockTillKeyPress(ConsoleKey.Enter); } fileStream.Dispose(); }
protected override void RunProxyImpl(CommandSettings settings) { // argument checks Debug.Assert(settings != null); using (ControllerThreadSynchronizer synchronizer = new ControllerThreadSynchronizer()) { // prepare Ctrl+C handler ConsoleCancelEventHandler onCtrlC = (o, e) => { e.Cancel = true; AwakeControllerThread(ControllerThreadSynchronizer.EventKind.Quit); }; // connect Ctrl+C handler Console.CancelKeyPress += onCtrlC; try { ControllerThreadSynchronizer.EventKind eventKind = ControllerThreadSynchronizer.EventKind.None; do { Debug.Assert(eventKind == ControllerThreadSynchronizer.EventKind.None || eventKind == ControllerThreadSynchronizer.EventKind.Resume); // run the proxy bool completed = false; using (RunningProxyState runningProxyState = StartProxy(settings, saveCredentials: true, checkPreviousBackup: false)) { // log & message LogProxyStarted(eventKind == ControllerThreadSynchronizer.EventKind.Resume); Console.WriteLine(Resources.CLICommandBase_Message_StartListening); Console.WriteLine(Resources.CLICommandBase_Message_StartingNote); // wait for Ctrl+C or other events RegisterControllerThreadSynchronizer(synchronizer); eventKind = synchronizer.WaitForEvent(); // stop the proxy completed = runningProxyState.Stop(eventKind == ControllerThreadSynchronizer.EventKind.SystemSessionEnding, 5000); } LogProxyStopped(completed, eventKind == ControllerThreadSynchronizer.EventKind.Suspend); Console.WriteLine(completed ? Resources.CLICommandBase_Message_Completed : Resources.CLICommandBase_Message_NotCompleted); // resume the thread which originally accepts the event synchronizer.NotifyEventHandledAndWaitForAcknowledgment(); // decide the next step while (eventKind == ControllerThreadSynchronizer.EventKind.Suspend) { // wait for the next event RegisterControllerThreadSynchronizer(synchronizer); eventKind = synchronizer.WaitForEvent(); synchronizer.NotifyEventHandledAndWaitForAcknowledgment(); } if (eventKind != ControllerThreadSynchronizer.EventKind.Resume) { // quit Debug.Assert(eventKind == ControllerThreadSynchronizer.EventKind.Quit || eventKind == ControllerThreadSynchronizer.EventKind.SystemSessionEnding); break; } } while (true); } finally { // disconnect Ctrl+C handler Console.CancelKeyPress -= onCtrlC; } } return; }
void DisposeProver() { if (cancelEvent != null) { Console.CancelKeyPress -= cancelEvent; cancelEvent = null; } }
static void Main(string[] args) { var client = new DiscordClient(); List <ICommand> Commands = new List <ICommand>(); List <IPermanent> Permanents = new List <IPermanent>(); client.Log.Message += Log_Message; saveDelegate = (object o, ConsoleCancelEventArgs e) => { Permanents.ForEach(p => { p.Save(client); }); client.Log.Log(LogSeverity.Info, "botchan", "Everything has been saved."); Thread.Sleep(500); }; Console.CancelKeyPress += saveDelegate; var searchspace = @"RPgrojectBot"; var q = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass && t.Namespace == searchspace && (t.GetInterfaces().Contains(typeof(ICommand)) || t.GetInterfaces().Contains(typeof(IPermanent))) select t; foreach (Type t in q) { var obj = t.InvokeMember("", BindingFlags.CreateInstance, null, null, null); if (t.GetInterfaces().Contains(typeof(ICommand))) { Commands.Add(obj as ICommand); } if (t.GetInterfaces().Contains(typeof(IPermanent))) { Permanents.Add(obj as IPermanent); } } foreach (IPermanent p in Permanents) { p.Load(client); } client.MessageReceived += async(s, e) => { if (e.User.Id != client.CurrentUser.Id) { var validCommands = Commands.Where(c => { return(e.Message.RawText.StartsWith(c.getToken())); }); if (validCommands.Count() > 0) { var longestCommandLen = validCommands.Max(c => { return(c.getToken().Length); }); var command = validCommands.Where(c => { return(longestCommandLen == c.getToken().Length); }); await command.First().execute(e, e.Message.RawText.Substring(longestCommandLen).Trim(' '), client); } else if (e.Message.RawText == "-save" && e.User.Id == 95543627391959040) { await e.Channel.SendMessage("Saved"); Permanents.ForEach(p => { p.Save(client); }); } else if (e.Message.RawText == "-load" && e.User.Id == 95543627391959040) { await e.Channel.SendMessage("Loaded"); Permanents.ForEach(p => { p.Load(client); }); } } }; client.ExecuteAndWait(async() => { await client.Connect(Sensitive.Token); Thread.Sleep(100); client.Log.Log(LogSeverity.Info, "botchan", "RProjectBot.", null); client.Log.Log(LogSeverity.Info, "botchan", "Currently on servers: ", null); foreach (Server s in client.Servers) { client.Log.Log(LogSeverity.Info, "botchan", " " + s.Name + " with " + s.Users.Count() + " Users.", null); } }); }
static void Migrate(Options options, string[] args) { if (string.IsNullOrWhiteSpace(options.ConfigFile) == false) { if (File.Exists(options.ConfigFile) == false) { throw new FileNotFoundException("Could not find file " + options.ConfigFile); } Console.WriteLine("Using option file: " + options.ConfigFile); OptionXmlParser.ParseOptionFromFile(options, options.ConfigFile); } using (CancellationTokenSource cancelToken = new CancellationTokenSource()) { ConsoleCancelEventHandler onCtrlC = delegate(object sender, ConsoleCancelEventArgs cancelArgs) { // Wait for the process to end gracefully if we get CTRL+C, // otherwise, let it die without clean up if we get CTRL+Break. if (cancelArgs.SpecialKey == ConsoleSpecialKey.ControlC) { cancelArgs.Cancel = true; Console.WriteLine("CTRL+C was received, cleaning up..."); cancelToken.Cancel(); } }; try { Console.CancelKeyPress += onCtrlC; ILoggerFactory loggerFactory = LoggerFactory.Create( builder => { builder.AddConsole(); } ); ICommandRunner commandRunner = new CommandRunner( loggerFactory.CreateLogger <CommandRunner>(), options.IsVerbose, cancelToken.Token ); IMessageDisplayer messageDisplayer = new ConsoleMessageDisplayer(); int exitCode = commandRunner.Run("git", "svn --version"); if (exitCode != 0) { throw new PlatformNotSupportedException("git svn not installed"); } Migrator migrator = new Migrator( options, args, commandRunner, messageDisplayer, loggerFactory ); migrator.Initialize(); migrator.Run(); } catch (OperationCanceledException) { Console.WriteLine("CTRL+C was received, child processes have been killed."); } finally { Console.CancelKeyPress -= onCtrlC; } } }
private static void DoIt(IEnumerable <Bundle> bundles) { var verbosityLevel = CommandLineConfigs.CommandLineParseResult.CommandResult.GetVerbosityLevel(); var verbosityLogger = new VerbosityLogger(verbosityLevel); var canceled = false; using var cancelMutex = new Mutex(); var cancelProcessHandler = new ConsoleCancelEventHandler((sender, cancelArgs) => { cancelMutex.WaitOne(); try { if (!canceled) { canceled = true; Console.WriteLine(LocalizableStrings.CancelingMessage); } cancelArgs.Cancel = true; } finally { cancelMutex.ReleaseMutex(); } }); foreach (var bundle in bundles.ToList().AsReadOnly()) { verbosityLogger.Log(VerbosityLevel.Normal, string.Format(LocalizableStrings.UninstallNormalVerbosityFormat, bundle.DisplayName)); using var process = new Process { StartInfo = GetProcessStartInfo(bundle.UninstallCommand) }; Console.CancelKeyPress += cancelProcessHandler; if (!process.Start() || !process.WaitForExit(UNINSTALL_TIMEOUT)) { throw new UninstallationFailedException(bundle.UninstallCommand); } if (process.ExitCode != 0) { throw new UninstallationFailedException(bundle.UninstallCommand, process.ExitCode); } Console.CancelKeyPress -= cancelProcessHandler; cancelMutex.WaitOne(); try { if (canceled) { Environment.Exit(1); } } finally { cancelMutex.ReleaseMutex(); } } }
public static void Run(Configuration c) { Console.WriteLine(Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + @" 服务器进程启动。"); var ProcessorCount = Environment.ProcessorCount; var WorkThreadCount = c.NumThread.OnSome ? Math.Max(1, c.NumThread.Value) : ProcessorCount; Console.WriteLine(@"逻辑处理器数量: " + ProcessorCount.ToString()); Console.WriteLine(@"工作线程数量: {0}".Formats(WorkThreadCount)); using (var tp = new CountedThreadPool("Worker", WorkThreadCount)) using (var tpPurifier = new CountedThreadPool("Purifier", 2)) using (var tpLog = new CountedThreadPool("Log", 1)) using (var ExitEvent = new AutoResetEvent(false)) using (var Logger = new ConsoleLogger(tpLog.QueueUserWorkItem)) { Logger.Start(); LockedVariable <ConsoleCancelEventHandler> CancelKeyPressInner = null; CancelKeyPressInner = new LockedVariable <ConsoleCancelEventHandler>((sender, e) => { CancelKeyPressInner.Update(v => { return(null); }); e.Cancel = true; Console.WriteLine(Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + @" 命令行中断退出。"); ExitEvent.Set(); }); ConsoleCancelEventHandler CancelKeyPress = (sender, e) => { var f = CancelKeyPressInner.Check(v => v); if (f == null) { return; } f(sender, e); }; Console.CancelKeyPress += CancelKeyPress; var ChatContexts = new List <ServerContext>(); var ServerCloses = new List <Action>(); try { foreach (var s in c.Servers) { if (s.OnChat) { var ss = s.Chat; var ServerContext = new ServerContext(); ChatContexts.Add(ServerContext); ServerContext.EnableLogNormalIn = c.EnableLogNormalIn; ServerContext.EnableLogNormalOut = c.EnableLogNormalOut; ServerContext.EnableLogUnknownError = c.EnableLogUnknownError; ServerContext.EnableLogCriticalError = c.EnableLogCriticalError; ServerContext.EnableLogPerformance = c.EnableLogPerformance; ServerContext.EnableLogSystem = c.EnableLogSystem; ServerContext.EnableLogTransport = c.EnableLogTransport; ServerContext.ServerDebug = c.ServerDebug; ServerContext.ClientDebug = c.ClientDebug; ServerContext.Shutdown += () => { Console.WriteLine(Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + @" 远程命令退出。"); ExitEvent.Set(); }; if (c.EnableLogConsole) { ServerContext.SessionLog += Logger.Push; } var Protocols = new List <IServer>(); var Factory = new TaskFactory(tp); var PurifierFactory = new TaskFactory(tp); foreach (var p in ss.Protocols) { if (System.Diagnostics.Debugger.IsAttached) { Protocols.Add(StartProtocol(c, p, ServerContext, Factory, PurifierFactory)); } else { try { Protocols.Add(StartProtocol(c, p, ServerContext, Factory, PurifierFactory)); } catch (Exception ex) { var Message = Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + "\r\n" + ExceptionInfo.GetExceptionInfo(ex); Console.WriteLine(Message); FileLoggerSync.WriteLog("Error.log", Message); } } } ServerCloses.Add(() => { foreach (var Session in ServerContext.Sessions.AsParallel()) { Session.SessionLock.EnterReadLock();; try { if (Session.EventPump != null) { Session.EventPump.ServerShutdown(new Communication.ServerShutdownEvent { }); } } finally { Session.SessionLock.ExitReadLock(); } } foreach (var p in Protocols) { if (System.Diagnostics.Debugger.IsAttached) { StopProtocol(p); } else { try { StopProtocol(p); } catch (Exception ex) { var Message = Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + "\r\n" + ExceptionInfo.GetExceptionInfo(ex); Console.WriteLine(Message); FileLoggerSync.WriteLog("Error.log", Message); } } } if (c.EnableLogConsole) { ServerContext.SessionLog -= Logger.Push; } Console.WriteLine(@"ChatServerContext.RequestCount = {0}".Formats(ServerContext.RequestCount)); Console.WriteLine(@"ChatServerContext.ReplyCount = {0}".Formats(ServerContext.ReplyCount)); Console.WriteLine(@"ChatServerContext.EventCount = {0}".Formats(ServerContext.EventCount)); }); } else { throw new InvalidOperationException("未知服务器类型: " + s._Tag.ToString()); } } ExitEvent.WaitOne(); Console.CancelKeyPress -= CancelKeyPress; } finally { foreach (var a in ServerCloses) { a(); } } } Console.WriteLine(Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + @" 服务器进程退出完成。"); }
public static async Task Start() { string checkAgainResponse = ""; string filepath = null; using var cancellationTokenSource = new CancellationTokenSource(); ConsoleCancelEventHandler cancelHandler = (sender, args) => cancellationTokenSource.Cancel(); Console.CancelKeyPress += cancelHandler; do { Console.WriteLine("your password:"******"the hash is: {hash}"); if (filepath == null) { Console.WriteLine("file path to hash file:"); filepath = Console.ReadLine(); } if (File.Exists(filepath)) { filepath = Path.GetFullPath(filepath); Console.WriteLine(filepath); Console.WriteLine("search started"); var time = new Stopwatch(); time.Start(); await AnsiConsole.Progress() .StartAsync(async ctx => { // Define tasks var progressTask = ctx.AddTask("[green]Searching for password hash[/]");; var progressHandler = new Progress <double>(value => progressTask.Value = progressTask.Value); int occurrences = 0; try { occurrences = await PasswordChecker.FindPassword(hash, filepath, progressHandler, cancellationTokenSource.Token); } catch (OperationCanceledException ex) { Console.WriteLine("Canceled."); return; } time.Stop(); Console.WriteLine($"Search took {time.Elapsed}"); if (occurrences > 0) { Console.WriteLine($"Bad news: Your password was found inside the database. This password has been seen {occurrences} times before"); } else { Console.WriteLine("Good news: No occurences found"); } }); do { Console.WriteLine("Check another password? (Y/N)"); checkAgainResponse = Console.ReadLine(); }while (!checkAgainResponse.Equals("Y", StringComparison.CurrentCultureIgnoreCase) && !checkAgainResponse.Equals("N", StringComparison.CurrentCultureIgnoreCase)); } else { Console.WriteLine("filepath invaild or not found"); } } while (checkAgainResponse.Equals("Y", StringComparison.CurrentCultureIgnoreCase)); Console.CancelKeyPress -= cancelHandler; }
/// <summary> /// Run /// </summary> /// <param name="args"></param> public static void Run(string[] args) { if (args.Length < 3 || args.Length > 4) { Console.WriteLine($@"Usage: {args[0]} <path> <folder> <IsOverwriten> [msbuild]"); return; } Arguments = args; IsMsBuildInvoked = Arguments.Length == 4 && Arguments[3] == "msbuild"; var tokenSource = new CancellationTokenSource(); var tasks = new List <TaskEvent>(); ConsoleCancelEventHandler onCancel = null; try { if (!IsMsBuildInvoked) { var t0 = new TaskEvent { Name = "t0", Tag = tasks, OnRunning = async(sender, tea) => { Console.WriteLine(@"Press `CTRL+C' to abort the process..."); onCancel = (o, e) => { e.Cancel = true; tea.TokenSource?.Cancel(); }; // Establish an event handler to process key press events. Console.CancelKeyPress += onCancel; while (!tea.TokenSource.IsCancellationRequested) { if (Console.KeyAvailable) { Console.ReadKey(true); } else { await Task.Delay(250, tea.TokenSource.Token); } } }, OnExited = (sender, tea) => { tea.Task.Dispose(); (tea.Tag as List <TaskEvent>)?.Remove((sender as ExitedEvent)?.TaskEvent); } }; tasks.Add(t0); t0.AsyncMonitor(); } // ================================================================================= var t1 = new TaskEvent { Name = "t1", Tag = tasks, OnRunning = (sender, tea) => { var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = tea.TokenSource.Token }; var cardCount = InitializeCollection(out var setCollection); CreateResources(args, options, setCollection); var dlCount = setCollection.Sum(kvp => kvp.Value.DownloadCount); Console.WriteLine($@"Downloaded information for ({dlCount}/{cardCount}) file{(cardCount > 1 ? "s" : string.Empty)}."); }, OnExited = (sender, tea) => { tea.Task.Dispose(); (tea.Tag as List <TaskEvent>)?.Remove((sender as ExitedEvent)?.TaskEvent); } }; tasks.Add(t1); t1.AsyncMonitor(); // Wait for any the tasks to finish and send the other one a cancellation signal. var b = Task.WaitAny(tasks.Select(x => x.Task).ToArray(), tokenSource.Token); if (b == 0) { Console.CancelKeyPress -= onCancel; } tasks[tasks.Count > 1 && b == 0 ? 1 : 0].Cancel(); } catch (OperationCanceledException) { Debug.WriteLine(""); } catch (Exception ex) { Debug.Print("Exception messages:"); var ie = ex.InnerException; while (ie != null) { Debug.Print($" {ie.GetType().Name}: {ie.Message}"); ie = ie.InnerException; } } finally { Task.WaitAll(tasks.Select(y => y.Task).ToArray()); Debug.WriteLine(@"All Tasks Completed"); tokenSource.Dispose(); if (!IsMsBuildInvoked) { Console.WriteLine(@"Press any key to continue..."); Console.ReadKey(true); } } }
public static void Load() { #region DEBUG #region HANG Command .Make("hang", true) .SetFunc((a) => { Thread.Sleep(Int32.MaxValue); }); #endregion #region COLORS Command .Make("colors", true) .SetFunc((a) => { string Demo = Util.GetAlphabet("a-zA-Z0-9"); foreach (KeyValuePair <char, ConsoleColor> ColorPair in Terminal.Colors) { Terminal.CWriteLine("$f{0} - " + string.Format("${0}█████████ " + Demo, ColorPair.Key), ColorPair.Key); } }); #endregion #region HANG Command .Make("todo", true) .SetFunc((a) => { foreach (Command c in Program.Cmds) { if (!(c.Documented || c.Debug)) { Terminal.CWriteLine("$a{0}", c.Name.ToUpper()); } } }); #endregion #region DEBUG Command .Make("debug") .SetFunc((a) => { Program.Debug = !Program.Debug; Terminal.CWriteLine("$eDebug mode is " + Util.Enabled(Program.Debug)); }) .Describe("Enable debug mode"); #endregion #region PARSE Command .Make("parse", true) .SetFunc((a) => { Terminal.CWriteLine("$eString count: $f{0}", a.Count()); Terminal.CWriteLine("$eQuoted count: $f{0}", a.Count(ArgTypes.Quoted)); Terminal.CWriteLine("$eParameter count: $f{0}", a.Count(ArgTypes.ParamValue)); Terminal.CWriteLine("$eSwitch count: $f{0}", a.Count(ArgTypes.Switch)); for (int i = 0; i < a.Parsed.Count; i++) { ParsedArg p = a.Parsed[i]; Terminal.CWriteLine("$a[{0}] $d[$f{1}$d] $e({2})", i, p.Value, p.TypeName()); } }); #endregion #endregion #region GENERAL #region CLS Command .Make("cls") .Alias("clear") .SetFunc((a) => { Terminal.Clear(); }) .Describe("Clears console window"); #endregion #region HELP Command .Make("help") .SetFunc((a) => { if (a.Get(1).Length > 0) { Command C = Program.FindCommand(a.Get(1)); if (C == null) { Regex r = Util.GenericRegex(a.Get(1), a, true); List <Command> Matched = new List <Command>(); foreach (Command c in Program.Cmds) { if (r.IsMatch(c.Name) || c.Aliases.Any(s => r.IsMatch(s))) { Matched.Add(c); } } if (Matched.Count > 0) { Terminal.CWriteLine("$aFound commands:"); foreach (Command c in Matched) { Program.SmallHelp(c); } } else { Terminal.CWriteLine("$cNothing found"); } return; } Program.Help(C); } else { Program.HelpAll(); } }) .Describe("Displays help message") .AddArg("Command", "Command to display help"); #endregion #region WHOAMI Command .Make("whoami") .SetFunc((a) => { Terminal.CWriteLine("Username: $a{0}", Util.UserName()); if (Util.IsAdmin()) { Terminal.CWriteLine("Administrator: $aTrue"); } else { Terminal.CWriteLine("Administrator: $cFalse"); } }) .Describe("Prints process owner"); #endregion #endregion #region STRING #region ALP Command .Make("alp") .SetFunc((a) => { if (a.FullArg().Length != 0) { try { string Alp = Util.GetAlphabet(a.FullArg()); a.PrintReturn("$a{0}", Alp); } catch (Exception) { Terminal.CWriteLine("$cInvalid input"); a.Return(""); return; } } a.PrintReturn("$a{0}", ""); }) .Raw(true) .Describe("Returns all ASCII characters that match regex") .AddArg("Regex", "Match to be used", true); #endregion #region RSTR // \[([^\]]+?)\]\{(\d+)(?:,(\d+))?\} Regex FindKey = new Regex("\\[([^\\]]+?)\\]\\{(\\d+)(?:,(\\d+))?\\}", Program.GeneralUseRegex); Command .Make("rstr") .Alias("keygen") .SetFunc((a) => { int Count = a.IntParam("c", 1); for (int i = 0; i < Count; i++) { string KeyFormat = a.Get(1); string Value = FindKey.Replace(KeyFormat, (m) => { string Range = m.Groups[1].Value; int Min = Util.ParseInt(m.Groups[2].Value); int Max = Util.ParseInt(m.Groups[3].Value, Min); int Len = Min == Max ? Min : Util.Rnd(Min, Max); return(Util.RandomString(Len, Util.GetAlphabet(Range))); }); Terminal.CWriteLine("$a{0}", Value); } }) .Param("c", "1") .Describe("Generates a random string based on a regex-style template") .DescribeParam("c", "Ammount of strings to generate") .AddArg("Template", "[Characters]{MinLength,MaxLength} e.g: [a-z\\d]{5,8}", true); #endregion #endregion #region FILE SYSTEM #region OL Command .Make("ol", false) .SetFunc((a) => { Process.Start(new ProcessStartInfo { FileName = "explorer.exe", Arguments = Program.Executable.Directory.FullName }); }) .Describe("Opens folder containing Dewy's executable"); #endregion #region LS Dictionary <char, FileAttributes> FileA = new Dictionary <char, FileAttributes>() { { 'd', FileAttributes.Directory }, { 'h', FileAttributes.Hidden }, { 'r', FileAttributes.ReadOnly }, { 's', FileAttributes.System }, }; Command .Make("ls") .SetFunc((a) => { string[] Files = Util.FetchFiles(a.Get(1), a); foreach (string F in Files) { FileInfo f = new FileInfo(F); string Attr = ""; foreach (KeyValuePair <char, FileAttributes> Fa in FileA) { try { if ((f.Attributes & Fa.Value) == Fa.Value) { Attr += Fa.Key; } else { Attr += '-'; } } catch (Exception) { Attr += '?'; } } Terminal.CWriteLine("$f[$a{0}$f] $a{1}", Attr, f.Name); } }) .Preset(Preset.FetchFile) .Describe("Lists files and directories") .AddArg("Match", "Matches file or directory name"); #endregion #region ATTR Dictionary <char, FileAttributes> Attrs = new Dictionary <char, FileAttributes>() { { 'r', FileAttributes.ReadOnly }, { 'h', FileAttributes.Hidden }, { 's', FileAttributes.System }, { 't', FileAttributes.Temporary }, { 'o', FileAttributes.Offline }, { 'i', FileAttributes.NotContentIndexed }, }; Attrs['*'] = Attrs.Select(o => o.Value).Aggregate((a, b) => (a | b)); Dictionary <char, Action <FileInfo, char> > AttrActions = new Dictionary <char, Action <FileInfo, char> >() { { '+', (f, m) => { f.Attributes = f.Attributes | Attrs[m]; } }, { '-', (f, m) => { f.Attributes = f.Attributes & ~Attrs[m]; } }, { '~', (f, m) => { f.Attributes = f.Attributes ^ Attrs[m]; } }, }; Regex AttrReg = new Regex(string.Format("([{0}][^{0}]*)", string.Join("", AttrActions.Select(o => "\\" + o.Key).ToArray())), Program.GeneralUseRegex); Command .Make("attr") .SetFunc((a) => { foreach (string Filn in Util.FetchFiles(a.Get(1), a)) { FileInfo f = new FileInfo(Filn); foreach (string s in a.VarArgs().Skip(2)) { foreach (Match m in AttrReg.Matches("+" + s)) { string Arg = m.Groups[0].Value.ToLower(); Terminal.CWriteLine(Arg); if (Arg.Length == 1) { continue; } char Mode = Arg[0]; string Att = Arg.Substring(1); foreach (char c in Att) { AttrActions[Mode](f, c); } } } string Attr = Util.FilAttr(f, Attrs); Terminal.CWriteLine("$f[$a{0}$f] $a{1}", Attr, f.Name); } }) .Preset(Preset.FetchFile) .Describe("View and modify file/directory attributes") .AddArg("Filename", "File to be matched", true) .AddArg("Attributes", "Format: [[Operator][Attributes]]+ i.e: +hr-s", false, true) .AddText("Attributes:", string.Join("\n", Attrs.Select(o => string.Format("$a{0} $f- {1}", o.Key, Util.EnumName(typeof(FileAttributes), (int)o.Value))).ToArray())) .AddText("\n$fOperators: $a" + string.Join(" ", AttrActions.Select(o => o.Key + "").ToArray())); #endregion #region CD Command .Make("cd") .SetFunc((a) => { if (a.FullArg().Length != 0) { DirectoryInfo Dir = Util.FindDir(a.FullArg()); if (Dir != null) { Environment.CurrentDirectory = Util.PrettyDir(Dir.FullName); } } Terminal.CWriteLine("$a{0}", Environment.CurrentDirectory); }) .Raw(true) .Describe("Changes working directory") .AddArg("Dir", "Directory name"); #endregion #region MKDIR Command .Make("mkdir") .Raw(true) .SetFunc((a) => { foreach (string Arg in a.VarArgs()) { try { Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, Arg)); Terminal.CWriteLine("$a{0}/", Arg); } catch (Exception e) { Terminal.CWriteLine("$c{0}/ - {1}", Arg, e.GetType().Name); } } }) .Describe("Creates directories") .AddArg("Dir", "Directory name", false, true); #endregion #region WRITE Command .Make("write") .Alias("w") .SetFunc((a) => { string FileName = a.Get(1); try { string Fil = Path.Combine(Environment.CurrentDirectory, a.Get(1)); File.WriteAllText(Fil, a.Get(2)); Terminal.CWriteLine("$aWrote {0} bytes.", new FileInfo(Fil).Length); } catch (Exception) { Terminal.CWriteLine("$cCouldn't write to file."); } }) .Describe("Writes data to files") .AddArg("Filename", "File to write to", true) .AddArg("Text", "Text to be written"); #endregion #region DEL Command .Make("del", true) .SetFunc((a) => { int time = Environment.TickCount; string[] Files = Util.FindAllRecur(a.Get(1), a); Terminal.CWriteLine("$aFile count: $f{0}", Files.Length); Terminal.CWriteLine("$aTime: $f{0}ms", Environment.TickCount - time); }) .Preset(Preset.Regex); #endregion #region FREGEX Regex FiMatch = new Regex("[\u0020-\u007E]+", Program.GeneralUseRegex); Command .Make("fregex") .Alias("fr") .SetFunc((a) => { Regex Re = null; try { Re = new Regex("^(.*)(" + a.Get(2) + ")(.*)$", RegexOptions.IgnoreCase); } catch (Exception) { Terminal.CWriteLine("$cInvalid regex"); return; } FileInfo Fi = Util.FindFile(a.Get(1)); if (Fi == null) { Terminal.CWriteLine("$cInvalid file"); return; } string Content = File.ReadAllText(Fi.FullName); int MinLen = a.IntParam("l", 4); Terminal.SetForeColor('8'); foreach (Match m in FiMatch.Matches(Content)) { string Text = m.Value; if (Text.Length < MinLen) { continue; } if (Re.IsMatch(Text)) { Match M = Re.Match(Text); string Pre = M.Groups[1].Value.TrimStart(); string Mat = M.Groups[2].Value; string Pos = M.Groups[3].Value.TrimEnd(); Terminal.CWriteLine("$7{0}$a{1}$7{2}", Pre, Mat, Pos); } } }) .Param("l") .DescribeParam("l", "Minimum match length to be processed") .AddArg("FileName", "File to be matched", true) .AddArg("Match", "Regex to be used") .Describe("Finds matches in files"); #endregion #region DIGI Regex Passw = new Regex(".*(passw|password|login|senha|begin ssh|begin pgp).*", Program.GeneralUseRegex); Environment.SpecialFolder[] UserFolders = new Environment.SpecialFolder[] { Environment.SpecialFolder.ApplicationData, Environment.SpecialFolder.MyPictures, Environment.SpecialFolder.MyMusic, Environment.SpecialFolder.MyDocuments, Environment.SpecialFolder.StartMenu, Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolder.Favorites, Environment.SpecialFolder.Personal, Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolder.InternetCache, Environment.SpecialFolder.History, Environment.SpecialFolder.Cookies, }; string[] IgnoreFormats = new string[] { "png", "jpg", "gif", "jpe", "jpeg", "mp3", "wav", "mkv", "mp4", "avi", "dll", "exe" }; Command .Make("digi") .SetFunc((a) => { HashSet <string> Matches = new HashSet <string>(); HashSet <string> ToSearch = new HashSet <string>(); bool Verbose = a.Switch("v"); ToSearch.Add(Environment.ExpandEnvironmentVariables("%appdata%\\Notepad++\\backup")); DriveInfo.GetDrives() .Where(o => o.DriveType == DriveType.Fixed && o.IsReady) .Each(o => ToSearch.Add(o.Name)); foreach (Environment.SpecialFolder s in UserFolders) { ToSearch.Add(Environment.GetFolderPath(s)); } List <string> Searched = new List <string>(); string[] FinalList = ToSearch.Where(o => o != string.Empty && Directory.Exists(o)).ToArray(); if (!Verbose) { Terminal.CWriteLine("$cWorking..."); } int Level = a.IntParam("l", 2); int time = Environment.TickCount; Action <string, int> Iter = null; Iter = (Dir, Count) => { if (++Count > Level) { return; } if (Searched.Contains(Dir)) { return; } Searched.Add(Dir); if (Verbose) { Terminal.CWriteLine("$c{0}", Dir); } string[] Files = null; try { Files = Directory.GetFileSystemEntries(Dir); } catch (Exception) { return; } foreach (string Fil in Files) { if (Directory.Exists(Fil)) { Iter(Fil, Count); continue; } FileInfo fi = new FileInfo(Fil); if (IgnoreFormats.Contains(fi.Name.Split('.').Last())) { continue; } if (Passw.IsMatch(fi.Name)) { Matches.Add(Fil); Terminal.CWriteLine("$a{0}", Fil); continue; } if (fi.Length < 1024 * 1) { try { string Data = File.ReadAllText(fi.FullName); if (Passw.IsMatch(Data)) { Matches.Add(Fil); Terminal.CWriteLine("$a{0}", Fil); } } catch (Exception) { } } } }; foreach (string Dir in FinalList) { Iter(Dir, 0); } if (Verbose) { foreach (string Fil in Matches) { Terminal.CWriteLine("$a{0}", Fil); } } if (a.Param("d").Trim().Length > 0) { try { DirectoryInfo Dir = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, a.Param("d"))); if (!Dir.Exists) { Dir.Create(); } Terminal.CWriteLine("$eDumping files..."); int i = 0; foreach (string Fil in Matches) { FileInfo fi = new FileInfo(Fil); try { fi.CopyTo(Path.Combine(Dir.FullName, string.Format("{0}-{1}", ++i, fi.Name))); } catch (IOException) { } } } catch (Exception) { Terminal.CWriteLine("$cFailed to dump"); } } Terminal.CWriteLine("$eProcess took {0}ms", Environment.TickCount - time); }) .Params("d", "l") .Switch("v") .DescribeParam("d", "Dump directory") .DescribeParam("l", "Recursion level") .DescribeSwitch("v", "Print current directory - Verbose") .Describe("Digs computer for login information"); #endregion #region PATH Command .Make("path") .SetFunc((a) => { string[] Paths = Environment.GetEnvironmentVariable("path").Split(';'); HashSet <string> NewPath = new HashSet <string>(); foreach (string S in Paths) { if (S.Length != 0 && Directory.Exists(S)) { NewPath.Add(S); } } foreach (string S in NewPath) { DirectoryInfo Dir = new DirectoryInfo(S); Terminal.CWriteLine("$a{0}", Dir.FullName.TrimEnd('\\')); } }) .Describe("Prints all directories in the PATH environment variable"); #endregion #region SEARCH Command .Make("search") .SetFunc((a) => { a.Return(Util.Search(a.Get(1), a, 2)); }) .Preset(Preset.Regex) .Describe("Searches directories recursively for files") .AddArg("Match", "Match for filename"); #endregion #region DL Command .Make("dl", true) .SetFunc((a) => { Action <string> Dl = (Url) => { try { if (!Url.Contains("://")) { Url = "http://" + Url; } Uri DlUrl = new Uri(Url); string Out = a.Get(2); Util.DownloadFile(DlUrl, Out); } catch (FieldAccessException e) { Terminal.CWriteLine("$c{0}", e.Message); } }; if (a.Param("l").Length > 0) { FileInfo Urls = Util.FindFile(a.Param("l")); string[] Lines = File.ReadAllLines(Urls.FullName); foreach (string LUrl in Lines) { Dl(LUrl); } } else { Dl(a.Get(1)); } }) .Cleanup(() => { foreach (WebClient wc in Util.WorkingWC) { try { wc.CancelAsync(); wc.Dispose(); } catch (Exception) { } } Util.WorkingWC.Clear(); }) .Param("l"); #endregion #region INSTALL Command .Make("install") .SetFunc((a) => { try { FileInfo Old = new FileInfo(Util.DewyPath()); FileInfo New = new FileInfo(Path.Combine(Environment.ExpandEnvironmentVariables("%systemroot%"), "Dewy.exe")); if (New.Exists) { New.Delete(); } Old.CopyTo(New.FullName); Process p = Process.Start(New.FullName); Environment.Exit(0); } catch (Exception) { Terminal.CWriteLine("$cAccess denied"); } }) .Describe("Installs dewy into Windows directory"); #endregion #region NAV Dictionary <char, FileAttributes> NavA = new Dictionary <char, FileAttributes>() { { 'h', FileAttributes.Hidden }, { 'r', FileAttributes.ReadOnly }, { 's', FileAttributes.System }, }; Command .Make("nav") .SetFunc((a) => { while (!a.Exit) { string Accessing = ""; try { Accessing = Environment.CurrentDirectory; DirectoryInfo Parent = new DirectoryInfo(Environment.CurrentDirectory); List <DirectoryInfo> Directories = Parent.GetDirectories().ToList(); if (Parent.Parent != null) { Directories = Util.Array(Parent.Parent).Concat(Directories).ToList(); } int Cur = 0; Terminal.CWriteLine("$e> {0}", Parent.FullName); foreach (DirectoryInfo Dir in Directories) { string Attr = Util.DirAttr(Dir, NavA); if (Parent.Parent != null && Dir.FullName == Parent.Parent.FullName) { Terminal.CWriteLine("$a[{0}] $e{1} $f{2}", (Cur++).ToString().PadLeft(3), Attr, ".."); } else { Terminal.CWriteLine("$a[{0}] $e{1} $f{2}", (Cur++).ToString().PadLeft(3), Attr, Dir.Name); } } int Index = -1; while (Index < 0 || Index >= Directories.Count()) { string Input = Terminal.PrettyInput(); if (Input == null) { a.Exit = true; break; } Index = Util.ParseInt(Input, -1); } if (a.Exit) { break; } Accessing = Directories[Index].FullName; Environment.CurrentDirectory = Directories[Index].FullName; } catch (UnauthorizedAccessException) { Terminal.CWriteLine("$cError accessing {0}", new DirectoryInfo(Accessing).Name); Environment.CurrentDirectory = Path.Combine(Accessing, ".."); } } Terminal.CWriteLine("$cClosed nav mode"); }) .Describe("Makes navigating through directories easier"); #endregion #region RN Command .Make("rn") .SetFunc((a) => { Dictionary <string, string> TempFiles = new Dictionary <string, string>(); Util.FetchFiles(a.Get(1), a).Each(f => { FileInfo F = new FileInfo(f); string Original = F.FullName; string NewName = Util.RandomString(18) + ".tmp"; F.MoveTo(NewName); TempFiles[Original] = new FileInfo(Path.Combine(F.Directory.FullName, NewName)).FullName; }); int i = 0; Regex Re = Util.GenericRegex(a.Get(1), a, true); Regex Replacer = new Regex("\\$([ir\\d\\$])", RegexOptions.IgnoreCase); int[] Randoms = new int[TempFiles.Count] .Select((v, k) => k) .OrderBy((p => Util.Rnd())) .ToArray(); foreach (KeyValuePair <string, string> Fil in TempFiles) { FileInfo Original = new FileInfo(Fil.Key); FileInfo Temp = new FileInfo(Fil.Value); Match Metch = Re.Match(Original.Name); string Result = Replacer.Replace(a.Get(2), (g) => { int w = -1; if (int.TryParse(g.Groups[1].Value, out w)) { if (Metch.Groups.Count < 2) { return(""); } return(Metch.Groups[w].Value); } switch (g.Groups[1].Value) { case "i": return(i.ToString()); case "r": return(Randoms[i].ToString()); case "$": return("$"); } return(""); }); i++; char p = (a.Param("m").Length > 0) ? (a.Param("m").ToLower()[0]) : '\0'; switch (p) { case 'u': Result = Result.ToUpper(); break; case 'l': Result = Result.ToLower(); break; } Terminal.CWriteLine("$a{0} $c=> $a{1}", Original.Name, Result); Temp.MoveTo(Result); } }) .Param("m") .DescribeParam("m", "String modifiers: [l]owercase [U]PPERCASE") .Describe("Renames files with regex like replace") .AddArg("Match", "Filename match i.e: *.*") .AddArg("Replace", "Replace pattern i.e: $1.png") .Preset(Preset.FetchFile); #endregion #region SRCH Command .Make("refind") .SetFunc((a) => { string Pattern = Util.GenericRegex(a.Get(1), a).ToString(); Regex Mc = new Regex(Pattern.Substring(1, Pattern.Length - 2)); Action <DirectoryInfo, int> Recur = null; Recur = (d, l) => { try { foreach (FileInfo f in d.GetFiles()) { string Text = File.ReadAllText(f.FullName); int Count = Mc.Matches(Text).Count; if (Count > 0) { Terminal.CWriteLine("$a{0}", Util.MakeRelative(f.FullName, Environment.CurrentDirectory)); } } if (l <= a.IntParam("l", 3)) { foreach (DirectoryInfo D in d.GetDirectories()) { Recur(D, l + 1); } } } catch (IOException) { } catch (UnauthorizedAccessException) { } }; DirectoryInfo Cur = new DirectoryInfo(Environment.CurrentDirectory); Recur(Cur, 0); }) .Param("l") .DescribeParam("l", "How many subdirectories to travel, default: 3") .Preset(Preset.Regex); #endregion #endregion #region NETWORK #region NETSTAT Command .Make("netstat") .SetFunc((a) => { Ping p = new Ping(); PingReply Reply = p.Send("8.8.8.8", 500); if (Reply.Status == IPStatus.Success) { Terminal.CWriteLine("$aConnection is up"); } else { Terminal.CWriteLine("$cConnection is down"); } }) .Describe("Simple way to tell if ethernet connection is up"); #endregion #region LIP Command .Make("lip") .Alias("localhost") .SetFunc((a) => { Terminal.CWriteLine("$dNAME $f| $eADDRESSES $f| $aDNS ADDRESSES\n"); foreach (NetworkInterface n in NetworkInterface.GetAllNetworkInterfaces()) { Terminal.CWriteLine("$d{0}", n.Name); IEnumerable <IPAddress> ips = n.GetIPProperties().UnicastAddresses.Select(i => i.Address); IEnumerable <IPAddress> dns = n.GetIPProperties().DnsAddresses; if (!a.Switch("6")) { ips = ips.Where(p => p.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); dns = dns.Where(p => p.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); } foreach (IPAddress d in ips) { Terminal.CWriteLine("$e{0}", d.ToString()); } foreach (IPAddress d in dns) { Terminal.CWriteLine("$a{0}", d.ToString()); } Terminal.WriteLine(); } }) .Switch("6") .DescribeSwitch("6", "Show IPV6 addresses") .Describe("Prints information about network interfaces"); #endregion #region IP Command .Make("ip") .SetFunc((a) => { using (WebClient w = new WebClient()) { try { a.PrintReturn("$a{0}", w.DownloadString("https://api.ipify.org")); return; } catch (Exception e) { Terminal.CWriteLine("$c{0}", e.Message); } } }) .Describe("Prints external Ip Address"); #endregion #endregion #region PROCESS #region EXIT Command .Make("exit") .Alias("quit") .SetFunc((a) => { Environment.Exit(0); Process.GetCurrentProcess().WaitForExit(); }) .Describe("Closes Dewy"); #endregion #region DIE Command .Make("die") .SetFunc((a) => { Process.GetCurrentProcess().Kill(); }) .Describe("Forcibly closes Dewy"); #endregion #region PKILL Command .Make("pkill") .Alias("pk") .SetFunc((a) => { foreach (string Pname in a.VarArgs()) { Regex r = Util.GenericRegex(Pname, a); foreach (Process Proc in Process.GetProcesses().OrderBy(o => o.Id)) { if (r.IsMatch(Proc.ProcessName)) { try { Proc.Kill(); Terminal.CWriteLine("$f[{0}] $e{1} $f- $aKilled", Proc.Id, Proc.ProcessName); } catch (Exception e) { Terminal.CWriteLine("$f[{0}] $e{1} $f- $c{2}", Proc.Id, Proc.ProcessName, e.GetType().Name); } } } } }) .Preset(Preset.Regex) .Describe("Kills processes") .AddArg("Match", "Matches process name", false, true); #endregion #region PKILL Command .Make("pkillid") .Alias("pkid") .SetFunc((a) => { int[] Pids = a.VarArgs().Select(o => Util.ParseInt(o, -1)).ToArray(); foreach (Process Proc in Process.GetProcesses().OrderBy(o => o.Id)) { if (Pids.Contains(Proc.Id)) { try { Proc.Kill(); Terminal.CWriteLine("$f[{0}] $e{1} $f- $aKilled", Proc.Id, Proc.ProcessName); } catch (Exception e) { Terminal.CWriteLine("$f[{0}] $e{1} $f- $c{2}", Proc.Id, Proc.ProcessName, e.GetType().Name); } } } }) .Preset(Preset.Regex) .Describe("Kills processes") .AddArg("Match", "Matches process name", false, true); #endregion #region PLIST Command .Make("plist") .Alias("pl") .SetFunc((a) => { foreach (string Pname in a.VarArgs(true)) { Regex r = Util.GenericRegex(Pname, a); foreach (Process Proc in Process.GetProcesses().OrderBy(o => o.Id)) { if (r.IsMatch(Proc.ProcessName)) { Terminal.CWriteLine("$f[{0}] $e{1}", Proc.Id, Proc.ProcessName); } } } }) .Preset(Preset.Regex) .Describe("Lists processes") .AddArg("Match", "Matches process name", false, true); #endregion #region ROOT Command .Make("root") .SetFunc((a) => { Process NewInstance = null; try { NewInstance = Process.Start(new ProcessStartInfo { FileName = Util.DewyPath(), Arguments = "", Verb = "runas", UseShellExecute = true }); } catch (Exception) { } if (NewInstance == null || NewInstance.HasExited) { Terminal.CWriteLine("$cFailed to start as administrator"); } else { Process.GetCurrentProcess().Kill(); } }) .Describe("Restarts Dewy as administrator"); #endregion #region START Command .Make("start") .SetFunc((a) => { Process Prc = null; FileInfo FileName = Util.FindFile(a.Get(1)); Exception exc = null; Terminal.SetForeColor('8'); if (FileName == null) { Terminal.CWriteLine("$cFile not found"); return; } try { Prc = Process.Start(new ProcessStartInfo { FileName = FileName.FullName, Arguments = a.Get(2), Verb = a.Switch("s") ? "runas" : "", UseShellExecute = a.Switch("n") }); } catch (Exception e) { exc = e; } ConsoleCancelEventHandler BlockCtrlC = delegate(object o, ConsoleCancelEventArgs e) { e.Cancel = true; }; Console.CancelKeyPress += BlockCtrlC; if (Prc == null || Prc.HasExited) { Terminal.CWriteLine("$cFailed to start process ({0})", exc); } else { Prc.WaitForExit(); } Terminal.SetForeColor('r'); Console.CancelKeyPress -= BlockCtrlC; }) .Switch("s", "n") .Describe("Runs processes") .DescribeSwitch("s", "Run as administrator") .DescribeSwitch("n", "Starts in a new window") .AddArg("FileName", "File to run", true) .AddArg("Arguments", "Arguments to start process"); #endregion #region PRIORITY Command .Make("priority") .Alias("pr") .SetFunc((a) => { Terminal.CWriteLine("$eAquiring maximum priority..."); Process p = Process.GetCurrentProcess(); try { p.PriorityBoostEnabled = true; p.PriorityClass = ProcessPriorityClass.RealTime; } catch (Exception) { } Terminal.CWriteLine("$aPriority: $e{0}", Enum.GetName(typeof(ProcessPriorityClass), p.PriorityClass)); Terminal.CWriteLine("$aBoost: $e{0}", p.PriorityBoostEnabled); }) .Describe("Sets Dewy's process priority to maximum"); #endregion #endregion #region PHP #region PHPSETUP PhpLib[] PhpLibs = null; Command .Make("phpsetup") .SetFunc((a) => { if (PhpLibs == null) { PhpLibs = Php.GetLibs(); int c = PhpLibs.Length; Terminal.CWriteLine("$aLoaded {0} lib{1}", c, Util.Sor(c)); } Terminal.CWriteLine("$eCreating directories..."); foreach (string Folder in Php.Folders) { try { string FullName = Path.Combine(Environment.CurrentDirectory, Folder); if (!Directory.Exists(FullName)) { Directory.CreateDirectory(FullName); Terminal.CWriteLine("$aCreated directory: $f{0}/", Folder); } } catch (Exception) { Terminal.CWriteLine("$cFailed to create directory: $f{0}", Folder); return; } } Terminal.CWriteLine("$eChecking libs..."); string Includes = ""; string IncFormat = "\t\t{0}\r\n"; using (WebClient w = new WebClient()) { foreach (PhpLib p in PhpLibs) { string FullName = Path.Combine(Environment.CurrentDirectory, p.FileName); if (!File.Exists(FullName)) { w.DownloadFile(p.Url, FullName); Terminal.CWriteLine("$aDownloaded $f{0}", p.Name); } string Ext = Path.GetExtension(p.FileName).TrimStart('.'); if (Php.Imports.ContainsKey(Ext)) { Includes += string.Format(IncFormat, string.Format(Php.Imports[Ext], p.FileName)); } else { Terminal.CWriteLine("$cUnknown lib format: $f{0}", Ext); } } } Terminal.CWriteLine("$eCreating files..."); File.WriteAllText("sys/header.php", string.Format(Php.Header, Includes)); Terminal.CWriteLine("$aCreated file: $f{0}", "sys/header.php"); foreach (KeyValuePair <string, string> Fil in Php.BaseFiles) { string FullName = Path.Combine(Environment.CurrentDirectory, Fil.Key); if (!File.Exists(FullName)) { File.WriteAllText(FullName, Fil.Value); Terminal.CWriteLine("$aCreated file: $f{0}", Fil.Key); } } }) .Describe("Creates php template with basic libraries"); #endregion #region PHPMAKE Command .Make("phpmake") .SetFunc((a) => { string Name = a.Get(1); string[] Files = new string[] { "{0}.php", "js/{0}.js", "css/{0}.css", }; foreach (string FileName in Files) { string Template = ""; try { Template = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, string.Format(FileName, "template"))); } catch (IOException) { } File.WriteAllText(Path.Combine(Environment.CurrentDirectory, string.Format(FileName, Name)), string.Format(Template, Name)); Terminal.CWriteLine("$aCreated file: $f{0}", string.Format(FileName, Name)); } }) .Describe("Creates php file and corresponding css and js") .AddArg("FileName", "Name for the file", true); #endregion #endregion }
public ConsoleHandler(ILogger logger) { this.logger = logger; EventHandler = new ConsoleCancelEventHandler(HandlerCallback); }
[PublicAPI] public ConsoleHandler(ILogger logger) { this.logger = logger; EventHandler = HandlerCallback; }
static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Use CTRL-C to enter commands or to communicate with the server."); Console.WriteLine("':?' will output help."); Console.ResetColor(); bool continueExecution = true; bool isInInterrupt = false; Console.CancelKeyPress += (sender, e) => { e.Cancel = true; isInInterrupt = true; Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("> "); var input = Console.ReadLine(); Console.ResetColor(); if (String.IsNullOrWhiteSpace(input)) { return; } if (input[0] == ':') { switch (input.Substring(1).ToLower()) { case "q": continueExecution = false; e.Cancel = false; break; case "?": case "h": default: Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(":? - displays this information."); Console.WriteLine(":h - displays this information."); Console.WriteLine(":q - exits the execution loop."); Console.ResetColor(); break; } isInInterrupt = false; return; } if (stream == null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Stream not yet connected. To quit, use ':q'"); Console.ResetColor(); } var bytes = Encoding.ASCII.GetBytes(input); stream.Write(bytes, 0, bytes.Length); stream.WriteByte(0); isInInterrupt = false; }; while (continueExecution) { try { ConsoleCancelEventHandler handler = (sender, e) => { continueExecution = false; }; using (var client = new TcpClient("localhost", 9090)) { stream = client.GetStream(); var buffer = new byte[1 << 11]; while (client.Connected) { if (!continueExecution) { break; } var read = stream.Read(buffer, 0, buffer.Length); if (read == 0) { break; } var str = Encoding.ASCII.GetString(buffer, 0, read); while (isInInterrupt) { Thread.Sleep(100); } Console.WriteLine(str); } } } catch (Exception ex) { while (isInInterrupt) { Thread.Sleep(100); } Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.Message); Console.ResetColor(); } } }
/// <summary> /// Run fuzzer /// </summary> /// <param name="action">Action</param> /// <param name="args">Arguments</param> public static void Run(Action <Stream> action, FuzzerRunArgs args = null) { CoverageHelper.CreateCoverageListener(); if (action == null) { throw new NullReferenceException(nameof(action)); } // Check supervisor Mutex mutex; var supervisor = FuzzerRunArgs.SupervisorType.None; if (args != null && args.Supervisor != FuzzerRunArgs.SupervisorType.None) { // Check if is the listener or the task with mutex mutex = new Mutex(false, "TuringMachine.Supervisor." + Client.PublicName, out var isNew); if (!isNew) { Client.PublicName += $".{Process.GetCurrentProcess().Id}:{args.TaskId}"; } else { Client.PublicName += ".Supervisor"; supervisor = args.Supervisor; } } else { mutex = null; } if (!Client.IsStarted) { // If you want other connection you must call this method before Run Client.Start(CommandLineOptions.Parse().GetConnection()); } // Send current files Client.SendCurrentFiles(new OperationCanceledException(), null, true); // Fuzz var cancel = new CancelEventArgs(); var handler = new ConsoleCancelEventHandler((o, s) => { cancel.Cancel = true; s.Cancel = true; }); Console.CancelKeyPress += handler; // Ensure data while (Client.GetInput() == null || Client.GetConfig() == null) { Thread.Sleep(50); } switch (supervisor) { case FuzzerRunArgs.SupervisorType.RegularSupervisor: { var pi = new ProcessStartInfoEx() { FileName = "dotnet", Arguments = string.Join(" ", Environment.GetCommandLineArgs().Select(u => u)), WindowStyle = ProcessWindowStyle.Normal, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = false, }; while (!cancel.Cancel) { using (var pr = new ProcessEx(pi)) { pr.WaitForExit(); Exception exception; switch (pr.ExitCode) { case StackOverflowExceptionCode: { exception = new StackOverflowException($"Unhandled exception: {pr.ExitCode}"); break; } default: { exception = new InvalidProgramException($"Unhandled exception: {pr.ExitCode}"); break; } } if (Client.SendCurrentFiles(exception, pr.Output, true) == 0) { Client.SendLog(new FuzzerLog() { Coverage = CoverageHelper.CurrentCoverage, InputId = Guid.Empty, ConfigId = Guid.Empty, }); } } } break; } case FuzzerRunArgs.SupervisorType.None: { while (!cancel.Cancel) { var input = Client.GetInput(); var config = Client.GetConfig(); string currentStreamPath = null; FileStream storeCurrentStream = null; if (args?.StoreCurrent == true) { // Free current stream currentStreamPath = $"{input.Id}.{config.Id}.{Process.GetCurrentProcess().Id}.{args.TaskId}.current"; storeCurrentStream = new FileStream(currentStreamPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); } using (var stream = new FuzzingStream(config, input, storeCurrentStream) { ExtraLogInformation = "TaskId: " + args.TaskId }) { var log = Client.Execute(action, stream); if (log != null) { Client.SendLog(log); args?.OnLog?.Invoke(log, cancel); } } if (storeCurrentStream != null) { // Delete current stream storeCurrentStream.Close(); storeCurrentStream.Dispose(); File.Delete(currentStreamPath); } } break; } } Console.CancelKeyPress -= handler; mutex?.Dispose(); }
public override void Execute() { AWSAuthConnection svc = new AWSAuthConnection(); IEnumerable <ListEntry> keys; if (!big) { if (key.EndsWith("*") || sub) { while (key.EndsWith("*")) { key = key.Substring(0, key.Length - 1); } IterativeList list = new IterativeList(bucket, key, regex); if (list.Count == IterativeList.EntryCount.some && explicitFilename) { throw new SyntaxException("You specified a destination filename but there is more than one key; can't copy multiple keys to one file"); } keys = list; } else { List <ListEntry> singleton = new List <ListEntry>(); singleton.Add(new ListEntry(key, DateTime.UtcNow, null, 0, null, null)); keys = singleton; } } else { if (key.EndsWith("*")) { throw new SyntaxException("Can't use wildcard (*) with the /big option"); } else { List <ListEntry> sorted = new List <ListEntry>(); foreach (ListEntry e in new IterativeList(bucket, key + ".", new Regex("^" + Regex.Escape(key) + @"\.\d{3,5}$"))) { sorted.Add(e); } if (sorted.Count == 0) { throw new FileNotFoundException("Not found: " + key + ".000"); } sorted.Sort(NumericSuffixCompare); keys = sorted; } } if (keys is IterativeList && (keys as IterativeList).Count == IterativeList.EntryCount.zero) { throw new FileNotFoundException("No keys found: " + key); } else { FileStream fs = null; ConsoleCancelEventHandler deletePartialFileHandler = delegate { if (fs != null) { try { fs.Close(); } catch { } File.Delete(fs.Name); Console.Error.WriteLine("Deleted partial file: " + fs.Name); } }; Console.CancelKeyPress += deletePartialFileHandler; try { if (big) { fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite); } int sequence = 0; foreach (ListEntry entry in keys) { string thisFilename = null; DateTime thisLastModified = DateTime.MinValue; if (!big) { if (sub) { if ("*" == Path.GetFileNameWithoutExtension(filename)) { // replace star with key/prefix: // bucket/path/prefix/[files] c:\local\* /sub ==> c:\local\path\prefix\[files] thisFilename = Path.Combine(Path.GetDirectoryName(filename), KeyToFilename(entry.Key)); } else { // strip key/prefix, leaving only filename: // bucket/path/prefix/[files] c:\local\ /sub ==> c:\local\[files] thisFilename = Path.Combine(filename, KeyToFilename(entry.Key.Substring(key.Length))); } string directoryName = Path.GetDirectoryName(thisFilename); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } } else if (explicitFilename) { thisFilename = filename; } else { thisFilename = entry.Key.Substring(entry.Key.LastIndexOf("/") + 1); } if (Path.GetFileName(thisFilename).Trim().Length == 0) { continue; } thisLastModified = File.GetLastWriteTimeUtc(thisFilename); fs = null; } else { if (!entry.Key.EndsWith(string.Format(".{0:000}", sequence))) { Console.Error.WriteLine(string.Format("Warning: The download has completed because there is no chunk number {0}, but there are chunks on S3 with higher numbers. These chunks were probably uploaded to S3 when the file was larger than it is now, but it could indicate a missing chunk. To surpress this message, delete the later chunks.", sequence)); break; } } Console.Write(string.Format("{0}/{1} {2} ", bucket, entry.Key, s3.Utils.FormatFileSize(entry.Size))); if (null != install) { install.SetFile(thisFilename, !File.Exists(thisFilename)); } try { GetResponse getResp = svc.getIfModifiedSince(bucket, entry.Key, thisLastModified, true); // may throw 304 if (fs == null) { fs = new FileStream(thisFilename, FileMode.Create, FileAccess.ReadWrite); } StreamToStream(getResp.Object.Stream, fs, md5 ? getResp.Connection.Headers["ETag"] : null, entry.Key, entry.Size); getResp.Object.Stream.Close(); if (!big) { fs.Close(); } getResp.Connection.Close(); sequence++; File.SetLastWriteTimeUtc(thisFilename, entry.LastModified); Console.WriteLine(); if (null != install) { // newer file downloaded install.SetFile(thisFilename, true); } } catch (WebException x) { if (x.Message.Contains("(304)")) { Console.WriteLine(" Not modified"); continue; } throw; } } if (big) { fs.Close(); } if (null != install) { install.InstallProducts(true); } } catch { deletePartialFileHandler(null, null); throw; } finally { Console.CancelKeyPress -= deletePartialFileHandler; } } }
internal ControlCDelegateData(ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks) { _controlKey = controlKey; _cancelCallbacks = cancelCallbacks; }
/// <summary> /// Orchestrates the execution of the application, and is also responsible /// for top-level error handling. /// </summary> /// <param name="commandLine">The command line to process. The first argument /// on the command line is assumed to be the name/path of the executable, and /// is ignored.</param> /// <returns>A value of type ExitType that indicates whether the build succeeded, /// or the manner in which it failed.</returns> public static ExitType Execute(string commandLine) { // Indicate to the engine that it can toss extraneous file content // when it loads microsoft.*.targets. We can't do this in the general case, // because tasks in the build can (and occasionally do) load MSBuild format files // with our OM and modify and save them. They'll never do this for Microsoft.*.targets, though, // and those form the great majority of our unnecessary memory use. Environment.SetEnvironmentVariable("MSBuildLoadMicrosoftTargetsReadOnly", "true"); string debugFlag = Environment.GetEnvironmentVariable("MSBUILDDEBUGONSTART"); if (debugFlag == "1") { Debugger.Launch(); } else if (debugFlag == "2") { // Sometimes easier to attach rather than deal with JIT prompt Console.ReadLine(); } ErrorUtilities.VerifyThrowArgumentLength(commandLine, "commandLine"); ExitType exitType = ExitType.Success; ConsoleCancelEventHandler cancelHandler = new ConsoleCancelEventHandler(Console_CancelKeyPress); try { #if (!STANDALONEBUILD) // Enable CodeMarkers for MSBuild.exe CodeMarkers.Instance.InitPerformanceDll(CodeMarkerApp.MSBUILDPERF, @"Software\Microsoft\MSBuild\4.0"); #endif #if MSBUILDENABLEVSPROFILING string startMSBuildExe = String.Format(CultureInfo.CurrentCulture, "Running MSBuild.exe with command line {0}", commandLine); DataCollection.CommentMarkProfile(8800, startMSBuildExe); #endif Console.CancelKeyPress += cancelHandler; // check the operating system the code is running on VerifyThrowSupportedOS(); // Setup the console UI. SetConsoleUI(); // reset the application state for this new build ResetBuildState(); // process the detected command line switches -- gather build information, take action on non-build switches, and // check for non-trivial errors string projectFile = null; string[] targets = { }; string toolsVersion = null; Dictionary<string, string> globalProperties = null; ILogger[] loggers = { }; LoggerVerbosity verbosity = LoggerVerbosity.Normal; List<DistributedLoggerRecord> distributedLoggerRecords = null; bool needToValidateProject = false; string schemaFile = null; int cpuCount = 1; bool enableNodeReuse = true; TextWriter preprocessWriter = null; bool debugger = false; bool detailedSummary = false; CommandLineSwitches switchesFromAutoResponseFile; CommandLineSwitches switchesNotFromAutoResponseFile; GatherAllSwitches(commandLine, out switchesFromAutoResponseFile, out switchesNotFromAutoResponseFile); if (ProcessCommandLineSwitches( switchesFromAutoResponseFile, switchesNotFromAutoResponseFile, ref projectFile, ref targets, ref toolsVersion, ref globalProperties, ref loggers, ref verbosity, ref distributedLoggerRecords, ref needToValidateProject, ref schemaFile, ref cpuCount, ref enableNodeReuse, ref preprocessWriter, ref debugger, ref detailedSummary, recursing: false )) { // Unfortunately /m isn't the default, and we are not yet brave enough to make it the default. // However we want to give a hint to anyone who is building single proc without realizing it that there // is a better way. if (cpuCount == 1 && FileUtilities.IsSolutionFilename(projectFile) && verbosity > LoggerVerbosity.Minimal) { Console.WriteLine(ResourceUtilities.FormatResourceString("PossiblyOmittedMaxCPUSwitch")); } if (preprocessWriter != null || debugger) { // Indicate to the engine that it can NOT toss extraneous file content: we want to // see that in preprocessing/debugging Environment.SetEnvironmentVariable("MSBUILDLOADALLFILESASWRITEABLE", "1"); } DateTime t1 = DateTime.Now; #if !STANDALONEBUILD if (Environment.GetEnvironmentVariable("MSBUILDOLDOM") != "1") #endif { // if everything checks out, and sufficient information is available to start building if (!BuildProject(projectFile, targets, toolsVersion, globalProperties, loggers, verbosity, distributedLoggerRecords.ToArray(), needToValidateProject, schemaFile, cpuCount, enableNodeReuse, preprocessWriter, debugger, detailedSummary)) { exitType = ExitType.BuildError; } } #if !STANDALONEBUILD else { exitType = OldOMBuildProject(exitType, projectFile, targets, toolsVersion, globalProperties, loggers, verbosity, needToValidateProject, schemaFile, cpuCount); } #endif DateTime t2 = DateTime.Now; TimeSpan elapsedTime = t2.Subtract(t1); string timerOutputFilename = Environment.GetEnvironmentVariable("MSBUILDTIMEROUTPUTS"); if (!String.IsNullOrEmpty(timerOutputFilename)) { AppendOutputFile(timerOutputFilename, elapsedTime.Milliseconds); } } else { // if there was no need to start the build e.g. because /help was triggered // do nothing } } /********************************************************************************************************************** * WARNING: Do NOT add any more catch blocks below! Exceptions should be caught as close to their point of origin as * possible, and converted into one of the known exceptions. The code that causes an exception best understands the * reason for the exception, and only that code can provide the proper error message. We do NOT want to display * messages from unknown exceptions, because those messages are most likely neither localized, nor composed in the * canonical form with the correct prefix. *********************************************************************************************************************/ // handle switch errors catch (CommandLineSwitchException e) { Console.WriteLine(e.Message); Console.WriteLine(); // prompt user to display help for proper switch usage ShowHelpPrompt(); exitType = ExitType.SwitchError; } // handle configuration exceptions: problems reading toolset information from msbuild.exe.config or the registry catch (InvalidToolsetDefinitionException e) { // Brief prefix to indicate that it's a configuration failure, and provide the "error" indication Console.WriteLine(ResourceUtilities.FormatResourceString("ConfigurationFailurePrefixNoErrorCode", e.ErrorCode, e.Message)); exitType = ExitType.InitializationError; } // handle initialization failures catch (InitializationException e) { Console.WriteLine(e.Message); exitType = ExitType.InitializationError; } // handle polite logger failures: don't dump the stack or trigger watson for these catch (LoggerException e) { // display the localized message from the outer exception in canonical format if (null != e.ErrorCode) { // Brief prefix to indicate that it's a logger failure, and provide the "error" indication Console.WriteLine(ResourceUtilities.FormatResourceString("LoggerFailurePrefixNoErrorCode", e.ErrorCode, e.Message)); } else { // Brief prefix to indicate that it's a logger failure, adding a generic error code to make sure // there's something for the user to look up in the documentation Console.WriteLine(ResourceUtilities.FormatResourceString("LoggerFailurePrefixWithErrorCode", e.Message)); } if (null != e.InnerException) { // write out exception details -- don't bother triggering Watson, because most of these exceptions will be coming // from buggy loggers written by users Console.WriteLine(e.InnerException.ToString()); } exitType = ExitType.LoggerAbort; } // handle logger failures (logger bugs) catch (InternalLoggerException e) { if (!e.InitializationException) { // display the localized message from the outer exception in canonical format Console.WriteLine("MSBUILD : error " + e.ErrorCode + ": " + e.Message); #if DEBUG Console.WriteLine("This is an unhandled exception from a logger -- PLEASE OPEN A BUG AGAINST THE LOGGER OWNER."); #endif // write out exception details -- don't bother triggering Watson, because most of these exceptions will be coming // from buggy loggers written by users Console.WriteLine(e.InnerException.ToString()); exitType = ExitType.LoggerFailure; } else { Console.WriteLine("MSBUILD : error " + e.ErrorCode + ": " + e.Message + (e.InnerException != null ? " " + e.InnerException.Message : "")); exitType = ExitType.InitializationError; } } catch (BuildAbortedException e) { Console.WriteLine("MSBUILD : error " + e.ErrorCode + ": " + e.Message + (e.InnerException != null ? " " + e.InnerException.Message : String.Empty)); exitType = ExitType.Unexpected; } // handle fatal errors catch (Exception e) { // display a generic localized message for the user Console.WriteLine("{0}\r\n{1}", AssemblyResources.GetString("FatalError"), e.ToString()); #if DEBUG Console.WriteLine("This is an unhandled exception in MSBuild Engine -- PLEASE OPEN A BUG AGAINST THE MSBUILD TEAM.\r\n{0}", e.ToString()); #endif // rethrow, in case Watson is enabled on the machine -- if not, the CLR will write out exception details // allow the build lab to set an env var to avoid jamming the build if (Environment.GetEnvironmentVariable("MSBUILDDONOTLAUNCHDEBUGGER") != "1") { throw; } } finally { s_buildComplete.Set(); Console.CancelKeyPress -= cancelHandler; // Wait for any pending cancel, so that we get any remaining messages s_cancelComplete.WaitOne(); #if (!STANDALONEBUILD) // Turn off codemarkers CodeMarkers.Instance.UninitializePerformanceDLL(CodeMarkerApp.MSBUILDPERF); #endif } /********************************************************************************************************************** * WARNING: Do NOT add any more catch blocks above! *********************************************************************************************************************/ return exitType; }
internal ControlCDelegateData(ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks) { this.ControlKey = controlKey; this.CancelCallbacks = cancelCallbacks; this.CompletionEvent = new ManualResetEvent(false); }
public Main(TerminalController te, int tid = 0) { this.Config(); this.tid = tid; VulnerFolder = new DirectoryInfo(Path.Combine(Environment.ExpandEnvironmentVariables("%appdata%"), Name.ToLower())); if (!VulnerFolder.Exists) { VulnerFolder.Create(); } if (Environment.GetCommandLineArgs().Contains("root")) { Process.Start(new ProcessStartInfo { FileName = Environment.GetCommandLineArgs()[0], Arguments = "runas", Verb = "runas", WindowStyle = ProcessWindowStyle.Normal, CreateNoWindow = false, }); Environment.Exit(0); return; } if (Environment.GetCommandLineArgs().Contains("update")) { int id = Process.GetCurrentProcess().Id; Process.GetProcesses().Where(t => t.ProcessName.ToLower().Contains(Name.ToLower()) && t.Id != id).Select(t => { t.Kill(); return(0); }); string self = Environment.GetCommandLineArgs().Skip(1).Where(t => t != "update").First(); #if (DEBUG) string vr = "Debug"; #else string vr = "Release"; #endif string dl = "https://github.com/Falofa/Vulner/blob/master/Vulner/bin/{0}/Vulner.exe?raw=true"; System.Net.WebClient wb = new System.Net.WebClient(); File.WriteAllBytes(self, wb.DownloadData(string.Format(dl, vr))); Process.Start(self, "updated"); Process.GetCurrentProcess().Kill(); return; } t = te; Groups = new Dictionary <string, CommandGroup>(); Cmds = new Commands().Get(this, t); Cmds[""] = new Command(); Environment.SetEnvironmentVariable(Name, Environment.GetCommandLineArgs()[0]); Environment.SetEnvironmentVariable("startup", Environment.GetFolderPath(Environment.SpecialFolder.Startup)); Environment.SetEnvironmentVariable("startmenu", Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)); string asciiName = @" $f║$c ____ ____ __ $fDeveloped by Falofa $f║ $f║$c \ \ / __ __| | ____ ___________ $f║ $f║$c \ Y | | | | / \_/ __ \_ __ \ $f║ $f║$c \ /| | | |_| | \ ___/| | \/ $f║ $f║$c \___/ |____/|____|___|__/\____/|__| $f║".Substring(2); string capt = " ╔═══════════════════════════════════════════════╗"; string capb = " ╚═══════════════════════════════════════════════╝"; #if (DEBUG) string build = "Debug Build"; #else string build = "Release Build"; #endif string fbuild = string.Format("$a[[ {0} ]]", build); fbuild = string.Format(" ║{0} $f║", fbuild.PadLeft(capt.Length - 3)); t.WriteLine(); t.ColorWrite(capt); t.ColorWrite(asciiName); t.ColorWrite(fbuild); t.ColorWrite(capb); t.WriteLine(); t.ColorWrite("$2Type $eHELP$2 for a list of commands"); if (Environment.GetCommandLineArgs().Contains("updated")) { t.ColorWrite("$a{0} was updated!", Name); } foreach (string s in Environment.GetCommandLineArgs()) { if (s.ToLower().EndsWith(".fal")) { if (!File.Exists(s.ToLower())) { Environment.Exit(1); } Environment.CurrentDirectory = new FileInfo(s.ToLower()).DirectoryName; Funcs.RunFile(s, this); break; } } Funcs.ShowConsole(); Funcs.EnableRightClick(); ConsoleCancelEventHandler ce = (o, e) => { if ((Environment.TickCount - LastKey) > 500) { FirstKey = Environment.TickCount; } LastKey = Environment.TickCount; if ((e.SpecialKey & ConsoleSpecialKey.ControlC) == ConsoleSpecialKey.ControlC) { killthread = true; if (CurrentArgumenter != null) { CurrentArgumenter.Quit = true; } } e.Cancel = true; }; Console.CancelKeyPress += ce; if (Environment.GetCommandLineArgs().Contains("emergency")) { Funcs.Emergency(te, this, true); } }
public static Task <int> Main(string[] args) { #if !NOCODEPAGES Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); #endif // !NOCODEPAGES var cliParser = new CommandLineBuilder(RootCommand()) .UseDefaults() .UseMiddleware(async(invokeCtx, next) => { var cts = new CancellationTokenSource(); var onCancelKeyPress = new ConsoleCancelEventHandler((object senter, ConsoleCancelEventArgs e) => { // If cancellation already has been requested, // do not cancel process termination signal. e.Cancel = !cts.IsCancellationRequested; cts.Cancel(throwOnFirstException: true); }); Console.CancelKeyPress += onCancelKeyPress; invokeCtx.BindingContext.AddService(typeof(CancellationTokenSource), () => cts); invokeCtx.BindingContext.AddService(typeof(CancellationToken), () => cts.Token); try { await next(invokeCtx).ConfigureAwait(false); } catch (OperationCanceledException) { } finally { Console.CancelKeyPress -= onCancelKeyPress; } }) .Build(); return(cliParser.InvokeAsync(args ?? Array.Empty <string>())); RootCommand RootCommand() { var root = new RootCommand(description); root.AddOption(new Option( new string[] { "-d", "--decode" }, "decode data (encodes by default)", new Argument <bool>() )); root.AddOption(new Option( new string[] { "-i", "--ignore-garbage" }, "when decoding, ignore non-alphabet characters", new Argument <bool>() )); root.AddOption(new Option( new string[] { "-w", "--wrap" }, "wrap encoded lines after COLS characters (default 76). Use 0 to disable line wrapping", WrapArgument() )); root.AddOption(new Option( new string[] { "-f", "--file" }, "Encode or decode contents of FILE ('-' for STDIN)", FileArgument() )); root.AddOption(new Option( new string[] { "-c", "--charset" }, $"use CHARSET when decoding data from a file (Default: {Encoding.UTF8.WebName}).", CharsetArgument() )); root.AddOption(new Option( new string[] { "-b", "--buffer" }, "use SIZE as the read-buffer size. (Default: 4096)", new Argument <int>(4096) { Name = "SIZE", Description = "Size to use for intermediate read buffer" } )); root.Handler = CommandHandler.Create(typeof(Program).GetMethod(nameof(InvokeAsync))); return(root); Argument <int?> WrapArgument() { var arg = new Argument <int?>(symbol => { if (symbol.Arguments.FirstOrDefault().TryNotNull(out string value)) { try { int number = int.Parse(value, NumberStyles.Integer, CultureInfo.CurrentCulture); return(ArgumentResult.Success <int?>(number)); } catch (OverflowException overflowExcept) { return(ArgumentResult.Failure(overflowExcept.Message)); } catch (FormatException formatExcept) { return(ArgumentResult.Failure(formatExcept.Message)); } } return(ArgumentResult.Success <int?>(76)); }) { Name = "COLS", Description = $"Number of characters per line (default {76})", Arity = ArgumentArity.ZeroOrOne }; arg.SetDefaultValue(null); arg.AddValidator(symbol => symbol.Arguments.Select(s => { if (int.TryParse(s, NumberStyles.Any, CultureInfo.CurrentCulture, out int v) && v >= 0) { return(null); } return($"Argument '{s}' for option '{symbol.Token}' is invalid. Expected a non-negative integer value."); }).Where(msg => !string.IsNullOrWhiteSpace(msg)).FirstOrDefault()); return(arg); } Argument <FileInfo> FileArgument() { var argument = new Argument <FileInfo> { Name = "FILE", Description = "Path to read from or write to", Arity = ArgumentArity.ExactlyOne }; argument.AddValidator(symbol => { IEnumerable <string> source = from filePath in symbol.Arguments where !filePath.Equals("-", StringComparison.Ordinal) where !File.Exists(filePath) select filePath; ValidationMessages validationMessages = symbol.ValidationMessages; return(source.Select(validationMessages.FileDoesNotExist).FirstOrDefault()); }); return(argument); } Argument <Encoding> CharsetArgument() { var arg = new Argument <Encoding>(ConvertToEncoding) { Arity = ArgumentArity.ZeroOrOne, Name = "CHARSET", Description = $"IANA charset name (default: {Encoding.UTF8})" }; arg.AddSuggestions(Encoding.GetEncodings().Select(enc => enc.Name).ToArray()); arg.SetDefaultValue(Encoding.UTF8); return(arg); ArgumentResult ConvertToEncoding(SymbolResult symbol) { if (symbol.Arguments.FirstOrDefault().TryNotNullOrWhiteSpace(out string charset)) { try { var encoding = Encoding.GetEncoding(charset); return(ArgumentResult.Success(encoding)); } catch (ArgumentException) { return(ArgumentResult.Failure($"Argument '{charset}' for option '{symbol.Token}' is invalid. '{charset}' is not a supported encoding name.")); } } return(ArgumentResult.Success(Encoding.UTF8)); } } } }