Skip to content

Commit

Permalink
🧹 Rewriting CLI Project.
Browse files Browse the repository at this point in the history
  • Loading branch information
Texnomic committed Jan 3, 2020
1 parent b3478e2 commit ccf3b8f
Show file tree
Hide file tree
Showing 6 changed files with 226 additions and 70 deletions.
6 changes: 3 additions & 3 deletions Texnomic.DNS.Servers/ProxyServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public class ProxyServer : IHostedService, IDisposable

private readonly UdpClient UdpClient;

public ProxyServer(IAsyncResponsibilityChain<IMessage, IMessage> ResponsibilityChain, ILogger Logger, int Threads = 0)
public ProxyServer(IAsyncResponsibilityChain<IMessage, IMessage> ResponsibilityChain, ILogger Logger, IPEndPoint IPEndPoint = null, int Threads = 0)
{
this.Threads = Threads == 0 ? Environment.ProcessorCount : Threads;

Expand All @@ -61,9 +61,9 @@ public ProxyServer(IAsyncResponsibilityChain<IMessage, IMessage> ResponsibilityC
//https://stackoverflow.com/questions/5199026/c-sharp-async-udp-listener-socketexception
UdpClient.Client.IOControl(-1744830452, new byte[4], null);

IPEndPoint = new IPEndPoint(IPAddress.Any, Port);
this.IPEndPoint = IPEndPoint ?? new IPEndPoint(IPAddress.Any, Port);

UdpClient.Client.Bind(IPEndPoint);
UdpClient.Client.Bind(this.IPEndPoint);

IncomingQueue = new BufferBlock<(IMessage, IPEndPoint)>();

Expand Down
3 changes: 2 additions & 1 deletion Texnomic.DNS/Protocols/HTTPs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@ public async Task<IMessage> ResolveAsync(IMessage Message)

private bool ValidateServerCertificate(object Sender, X509Certificate Certificate, X509Chain Chain, SslPolicyErrors SslPolicyErrors)
{
return SslPolicyErrors == SslPolicyErrors.None && Certificate.GetPublicKeyString() == PublicKey;
//return SslPolicyErrors == SslPolicyErrors.None && Certificate.GetPublicKeyString() == PublicKey;
return SslPolicyErrors == SslPolicyErrors.None;
}


Expand Down
198 changes: 138 additions & 60 deletions Texnomic.SecureDNS.CLI/App.cs
Original file line number Diff line number Diff line change
@@ -1,29 +1,48 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
using PipelineNet.MiddlewareResolver;
using Serilog;
using Terminal.Gui;
using Texnomic.DNS.Servers;
using Texnomic.DNS.Servers.ResponsibilityChain;

using Attribute = Terminal.Gui.Attribute;

namespace Texnomic.SecureDNS.CLI
{
public static class App
public class App
{
public static ActivatorMiddlewareResolver ActivatorMiddlewareResolver = new ActivatorMiddlewareResolver();
public static ProxyResponsibilityChain ServerResponsibilityChain = new ProxyResponsibilityChain(ActivatorMiddlewareResolver);
public static ProxyServer ProxyServer = new ProxyServer(ServerResponsibilityChain, Log.Logger);
public static CancellationToken CancellationToken = new CancellationToken();
public ProxyServer ProxyServer;

public Settings Settings;

public App(Settings Settings)
{
this.Settings = Settings;
}

private static readonly ColorScheme SuccessColorScheme = new ColorScheme()
{
Normal = Attribute.Make(Color.Black, Color.Green),
Focus = Attribute.Make(Color.Black, Color.Green)
};

private static readonly ColorScheme FailureColorScheme = new ColorScheme()
{
Normal = Attribute.Make(Color.White, Color.Red),
Focus = Attribute.Make(Color.White, Color.Red)
};

public static void Run()
public void Run()
{
Application.Init();

var Window = new Window("Texnomic SecureDNS", 1)
var Window = new Window("Management", 1)
{
X = 0,
Y = 1,
Expand All @@ -40,89 +59,63 @@ public static void Run()
Y = 2,
};

var ServerBindingText = new TextField("0.0.0.0:53")
var ServerBindingText = new TextField(Settings.ServerIPEndPoint.ToString())
{
X = Pos.Right(ServerBindingLabel) + 2,
Y = Pos.Top(ServerBindingLabel),
Width = 30
};

ServerBindingText.Changed += (Sender, Args) => CheckIPEndPoint(ServerBindingText);

var SeqEndPointLabel = new Label("Seq EndPoint: ")
{
X = Pos.Left(ServerBindingLabel),
Y = Pos.Top(ServerBindingLabel) + 2,
};

var SeqEndPointText = new TextField("http://127.0.0.1:5341")
var SeqEndPointText = new TextField(Settings.SeqUriEndPoint.ToString())
{
X = Pos.Right(SeqEndPointLabel) + 4,
Y = Pos.Top(SeqEndPointLabel),
Width = 30
Width = 30,
};

SeqEndPointText.Changed += (Sender, Args) => CheckUri(SeqEndPointText);

var StartButton = new Button("Start Server", true)
{
X = Pos.Left(SeqEndPointLabel),
Y = 14,
Clicked = async () =>
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Seq(SeqEndPointText.Text.ToString(), compact: true)
.CreateLogger();

await ProxyServer.StartAsync(CancellationToken);

MessageBox.Query(40, 7, "SecureDNS", "Server Started.", "OK");
}
X = Pos.AnchorEnd(37),
Y = Pos.AnchorEnd(1),
Clicked = async () => await Start()
};

var StopButton = new Button("Stop Server")
{
X = Pos.Right(StartButton) + 2,
Y = 14,
Clicked = async () =>
{
await ProxyServer.StopAsync(CancellationToken);

MessageBox.Query(40, 7, "SecureDNS", "Server Stopped.", "OK");
}
X = Pos.AnchorEnd(16),
Y = Pos.AnchorEnd(1),
Clicked = async () => await Stop()
};

var MenuBar = new MenuBar(new []
var MenuBar = new MenuBar(new[]
{
new MenuBarItem ("Server", new []
new MenuBarItem ("SecureDNS", new []
{
new MenuItem ("Start", "", async () =>
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Seq(SeqEndPointText.Text.ToString(), compact: true)
.CreateLogger();

await ProxyServer.StartAsync(CancellationToken);

MessageBox.Query(40, 7, "SecureDNS", "Server Started.", "OK");
}),
new MenuItem ("Start", "Server", async () => await Start()),

new MenuItem ("Stop", "", async () =>
{
await ProxyServer.StopAsync(CancellationToken);
new MenuItem ("Stop", "Server", async () => await Stop()),

MessageBox.Query(40, 7, "SecureDNS", "Server Stopped.", "OK");
}),
new MenuItem ("Quite", "System", Application.RequestStop),
}),

new MenuBarItem ("Seq", new []
{
new MenuItem ("Browse", "", () =>
{
var Seq = new ProcessStartInfo(SeqEndPointText.Text.ToString())
{
UseShellExecute = true,
Verb = "open"
};

Process.Start(Seq);
}),
new MenuItem ("Browse", "", () => Browse(SeqEndPointText.Text.ToString())),
}),

new MenuBarItem("About", new[]
{
new MenuItem("Browse", "GitHub", () => Browse("https://github.com/Texnomic/SecureDNS")),
})
});

Expand All @@ -138,5 +131,90 @@ public static void Run()

Application.Run();
}

private async Task Start()
{
try
{
var Available = CheckPort(IPEndPoint.Parse(Settings.ServerIPEndPoint).Port);

if (Available)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Seq(Settings.SeqUriEndPoint.ToString(), compact: true)
.CreateLogger();

var ActivatorMiddlewareResolver = new ActivatorMiddlewareResolver();

var ServerResponsibilityChain = new ProxyResponsibilityChain(ActivatorMiddlewareResolver);

ProxyServer = new ProxyServer(ServerResponsibilityChain, Log.Logger, IPEndPoint.Parse(Settings.ServerIPEndPoint));

await ProxyServer.StartAsync(Settings.CancellationToken);

MessageBox.Query(40, 7, "Information", "Server Started.", "OK");
}
else
{
MessageBox.ErrorQuery(80, 7, "Error", $"Port {IPEndPoint.Parse(Settings.ServerIPEndPoint).Port} Already Used.", "OK");
}
}
catch (Exception Error)
{
MessageBox.ErrorQuery(80, 7, "Error", Error.Message, "OK");
}
}

private async Task Stop()
{
try
{
await ProxyServer.StopAsync(Settings.CancellationToken);

MessageBox.Query(40, 7, "Information", "Server Stopped.", "OK");
}
catch (Exception Error)
{
MessageBox.ErrorQuery(80, 7, "Error", Error.Message, "OK");
}
}

private static void Browse(string Url)
{
var Ps = new ProcessStartInfo(Url)
{
UseShellExecute = true,
Verb = "open"
};

Process.Start(Ps);
}

private static bool CheckPort(int Port)
{
return IPGlobalProperties.GetIPGlobalProperties()
.GetActiveUdpListeners()
.All(Connection => Connection.Port != Port);
}

private void CheckIPEndPoint(TextField TextField)
{
var IsValid = IPEndPoint.TryParse(TextField.Text.ToString(), out var Result);

TextField.ColorScheme = IsValid ? SuccessColorScheme : FailureColorScheme;

Settings.ServerIPEndPoint = IsValid ? Result.ToString() : Settings.ServerIPEndPoint;
}

private void CheckUri(TextField TextField)
{
var IsValid = Uri.TryCreate(TextField.Text.ToString(), UriKind.Absolute, out var Result);

IsValid = IsValid && Result.Scheme == Uri.UriSchemeHttp;

TextField.ColorScheme = IsValid ? SuccessColorScheme : FailureColorScheme;

Settings.SeqUriEndPoint = IsValid ? Result.ToString() : Settings.SeqUriEndPoint;
}
}
}
54 changes: 49 additions & 5 deletions Texnomic.SecureDNS.CLI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net;
using Terminal.Gui;
using System.Threading;
using System.Threading.Tasks;
using Colorful;
using CommandLine;
using PipelineNet.MiddlewareResolver;
using Serilog;
using Texnomic.DNS.Servers;
using Texnomic.DNS.Servers.ResponsibilityChain;
using Texnomic.SecureDNS.CLI.Properties;
using Attribute = Terminal.Gui.Attribute;
using Console = Colorful.Console;

namespace Texnomic.SecureDNS.CLI
{
internal class Program
{
private static async Task Main(string[] args)
private static async Task Main(string[] Args)
{
try
{
Expand All @@ -28,19 +32,59 @@ private static async Task Main(string[] args)

Console.WriteWithGradient(Speed.ToAscii(" SecureDNS").ConcreteValue.ToArray(), System.Drawing.Color.Yellow, System.Drawing.Color.Fuchsia, 14);

Console.WriteLine(" > Loading...");
Console.WriteLine("");

Thread.Sleep(3000);
if (Args.Length == 0)
{
Console.WriteLine(" > Loading...");

Console.ReplaceAllColorsWithDefaults();
Console.WriteLine("");

App.Run();
Thread.Sleep(2500);

RunGUI();
}
else
{
Parser.Default.ParseArguments<Settings>(Args)
.WithParsed(RunCMD);
}

}
catch (Exception Error)
{
Console.WriteLine($"Fatal Error: {Error.Message}");
Console.ReadLine();
}
}

private static void RunCMD(Settings Settings)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Seq(Settings.SeqUriEndPoint.ToString(), compact: true)
.CreateLogger();

var ActivatorMiddlewareResolver = new ActivatorMiddlewareResolver();

var ServerResponsibilityChain = new ProxyResponsibilityChain(ActivatorMiddlewareResolver);

var ProxyServer = new ProxyServer(ServerResponsibilityChain, Log.Logger, IPEndPoint.Parse(Settings.ServerIPEndPoint));

ProxyServer.Started += (Sender, Args) => Console.WriteLine($"Server Started.");

ProxyServer.Stopped += (Sender, Args) => Console.WriteLine($"Server Stopped.");

ProxyServer.Errored += (Sender, Args) => Console.WriteLine($"Server Error: {Args.Error.Message}");

ProxyServer.StartAsync(Settings.CancellationToken).Wait();
}

private static void RunGUI()
{
Console.ReplaceAllColorsWithDefaults();

var App = new App(new Settings());
App.Run();
}
}
}
Loading

0 comments on commit ccf3b8f

Please sign in to comment.