Skip to content

Commit

Permalink
v3.2.1
Browse files Browse the repository at this point in the history
  • Loading branch information
msasanmh committed Jun 18, 2024
1 parent 0521833 commit edfb57c
Show file tree
Hide file tree
Showing 48 changed files with 1,583 additions and 1,245 deletions.
42 changes: 42 additions & 0 deletions MsmhToolsClass/MsmhToolsClass/ExtensionsMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,48 @@ public static bool TryUpdate<K, V>(this ConcurrentDictionary<K, V> ccDic, K key,
}
//-----------------------------------------------------------------------------------
/// <summary>
/// To List
/// </summary>
public static List<Tuple<string, string>> ToList(this NameValueCollection nvc)
{
List<Tuple<string, string>> result = new();

try
{
for (int n = 0; n < nvc.Count; n++)
{
string? key = nvc.GetKey(n);
string? val = nvc.Get(n);
if (string.IsNullOrEmpty(key)) continue;
if (string.IsNullOrEmpty(val)) continue;
result.Add(new Tuple<string, string>(key, val));
}
}
catch (Exception) { }

return result;
}
//-----------------------------------------------------------------------------------
/// <summary>
/// Get Value By Key
/// </summary>
/// <returns>Returns string.Empty If Key Not Exist Or Value Is Empty.</returns>
public static string GetValueByKey(this NameValueCollection nvc, string? key)
{
string result = string.Empty;
if (string.IsNullOrWhiteSpace(key)) return result;

try
{
string? value = nvc[key];
result = value ?? string.Empty;
}
catch (Exception) { }

return result;
}
//-----------------------------------------------------------------------------------
/// <summary>
/// If Key Exist Adds The Value (Comma-Separated)
/// </summary>
public static void AddAndUpdate(this NameValueCollection nvc, string? key, string? value)
Expand Down
54 changes: 46 additions & 8 deletions MsmhToolsClass/MsmhToolsClass/HttpRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,9 @@ public class HttpRequestResponse
public string ContentType { get; internal set; } = string.Empty;
public long ContentLength { get; internal set; } = 0;
public string ProtocolVersion { get; internal set; } = string.Empty;
public int StatusCode { get; internal set; } = (int)HttpStatusCode.NoContent;
public string StatusDescription { get; internal set; } = HttpStatusCode.NoContent.ToString();
public HttpStatusCode StatusCode { get; internal set; } = HttpStatusCode.RequestTimeout;
public int StatusCodeNumber { get; internal set; } = (int)HttpStatusCode.RequestTimeout;
public string StatusDescription { get; internal set; } = HttpStatusCode.RequestTimeout.ToString();
public NameValueCollection Headers { get; internal set; } = new(StringComparer.InvariantCultureIgnoreCase);
public byte[] Data { get; internal set; } = Array.Empty<byte>();

Expand All @@ -77,6 +78,7 @@ public override string ToString()
result += $"{nameof(ContentLength)}: {ContentLength}\r\n";
result += $"{nameof(ProtocolVersion)}: {ProtocolVersion}\r\n";
result += $"{nameof(StatusCode)}: {StatusCode}\r\n";
result += $"{nameof(StatusCodeNumber)}: {StatusCodeNumber}\r\n";
result += $"{nameof(StatusDescription)}: {StatusDescription}\r\n";
if (Headers.Count > 0)
result += $"{nameof(Headers)}:\r\n";
Expand Down Expand Up @@ -273,7 +275,7 @@ public static HttpRequestResult Read(byte[] buffer)

key = key.Trim();
val = val.Trim();

if (string.IsNullOrEmpty(key)) continue;
if (string.IsNullOrEmpty(val)) continue;
string keyEval = key.ToLower();
Expand Down Expand Up @@ -479,9 +481,10 @@ public static async Task<HttpRequestResponse> SendAsync(HttpRequest hr)

hrr.IsSuccess = response.IsSuccessStatusCode;
hrr.ProtocolVersion = $"HTTP/{response.Version}";
hrr.StatusCode = (int)response.StatusCode;
hrr.StatusCode = response.StatusCode;
hrr.StatusCodeNumber = (int)response.StatusCode;
hrr.StatusDescription = response.StatusCode.ToString();

hrr.ContentEncoding = string.Join(",", response.Content.Headers.ContentEncoding);
if (response.Content.Headers.ContentType != null)
hrr.ContentType = response.Content.Headers.ContentType.ToString();
Expand Down Expand Up @@ -520,12 +523,13 @@ public static async Task<HttpRequestResponse> SendAsync(HttpRequest hr)
{
hrr.IsSuccess = false;
hrr.ProtocolVersion = $"HTTP/{exceptionResponse.ProtocolVersion}";
hrr.StatusCode = (int)exceptionResponse.StatusCode;
hrr.StatusCode = exceptionResponse.StatusCode;
hrr.StatusCodeNumber = (int)exceptionResponse.StatusCode;
hrr.StatusDescription = exceptionResponse.StatusDescription;
hrr.ContentEncoding = exceptionResponse.ContentEncoding;
hrr.ContentType = exceptionResponse.ContentType;
hrr.ContentLength = exceptionResponse.ContentLength;

if (exceptionResponse.Headers != null && exceptionResponse.Headers.Count > 0)
{
for (int n = 0; n < exceptionResponse.Headers.Count; n++)
Expand Down Expand Up @@ -580,9 +584,43 @@ public static async Task<HttpRequestResponse> SendAsync(HttpRequest hr)
catch (Exception) { }
}
}
catch (HttpRequestException hre)
{
if (hre.StatusCode != null)
{
hrr.StatusCode = (HttpStatusCode)hre.StatusCode;
hrr.StatusCodeNumber = (int)hrr.StatusCode;
hrr.StatusDescription = hrr.StatusCode.ToString();
}
}
catch (Exception ex)
{
Debug.WriteLine("HttpRequest SendAsync: " + ex.GetInnerExceptions());
if (hr.URI == null)
Debug.WriteLine("HttpRequest SendAsync: " + ex.GetInnerExceptions());
else
{
try
{
string host = string.Empty;
for (int n = 0; n < hr.Headers.Count; n++)
{
string? key = hr.Headers.GetKey(n);
string? val = hr.Headers.Get(n);

if (string.IsNullOrEmpty(key)) continue;
if (string.IsNullOrEmpty(val)) continue;

if (key.ToLower().Trim().Equals("host"))
{
host = val;
break;
}
}
Debug.WriteLine($"HttpRequest SendAsync. URL: {hr.URI}, Host Header: {host}");
Debug.WriteLine("HttpRequest SendAsync: " + ex.GetInnerExceptions());
}
catch (Exception) { }
}
hrr.IsSuccess = false;
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ public static async Task Process(AgnosticResult aResult, AgnosticProgram.DnsRule

if (answers.Count != 0)
{
// Show Only 5 Records
if (answers.Count > 5) answers = answers.Take(5).ToList();
msgReqEvent += answers.ToString(", ");
onRequestReceived?.Invoke(msgReqEvent, EventArgs.Empty);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,17 @@ public void EnableDnsLimit(AgnosticProgram.DnsLimit dnsLimit)
private Socket? UdpSocket_;
private readonly DnsCache DnsCaches = new();
private readonly ProxyRequestsCache ProxyRequestsCaches = new();
private readonly CaptivePortal CaptivePortals = new();
private TcpListener? TcpListener_;
internal TunnelManager TunnelManager_ = new();

private CancellationTokenSource? CancelTokenSource_;
private CancellationToken CancelToken_;
private CancellationTokenSource CTS_PR = new();

private System.Timers.Timer KillOnOverloadTimer { get; set; } = new(5000);
private System.Timers.Timer KillOnOverloadTimer { get; set; } = new(10000);
private float CpuUsage { get; set; } = -1;
private static NetworkTool.InternetState InternetState = NetworkTool.InternetState.Online; // Default

private bool Cancel { get; set; } = false;

Expand All @@ -76,7 +78,6 @@ public void EnableDnsLimit(AgnosticProgram.DnsLimit dnsLimit)
public bool IsRunning { get; private set; } = false;

private readonly ConcurrentQueue<DateTime> MaxRequestsQueue = new();
private readonly ConcurrentDictionary<string, DateTime> DelinquentRequests = new();
private readonly ConcurrentDictionary<string, (DateTime dt, bool applyFakeSNI, bool applyFragment)> TestRequests = new();
internal static readonly int MaxRequestsDelay = 50;
internal static readonly int MaxRequestsDivide = 20; // 20 * 50 = 1000 ms
Expand All @@ -91,35 +92,43 @@ public async Task EnableSSL(AgnosticSettingsSSL settingsSSL)

public void Start(AgnosticSettings settings)
{
if (IsRunning) return;
IsRunning = true;
try
{
if (IsRunning) return;
IsRunning = true;

Settings_ = settings;
Settings_.Initialize();
Settings_ = settings;
Settings_.Initialize();

// Set Default DNSs
if (Settings_.DNSs.Count == 0) Settings_.DNSs = AgnosticSettings.DefaultDNSs();
// Set Default DNSs
if (Settings_.DNSs.Count == 0) Settings_.DNSs = AgnosticSettings.DefaultDNSs();

Stats = new Stats();
Stats = new Stats();

Welcome();
Welcome();

TunnelManager_ = new();
TunnelManager_ = new();

CancelTokenSource_ = new();
CancelToken_ = CancelTokenSource_.Token;
CancelTokenSource_ = new();
CancelToken_ = CancelTokenSource_.Token;

Cancel = false;
Cancel = false;

MaxRequestsTimer();
MaxRequestsTimer();

KillOnOverloadTimer.Elapsed += KillOnOverloadTimer_Elapsed;
KillOnOverloadTimer.Start();
KillOnOverloadTimer.Elapsed -= KillOnOverloadTimer_Elapsed;
KillOnOverloadTimer.Elapsed += KillOnOverloadTimer_Elapsed;
KillOnOverloadTimer.Start();

ThreadStart threadStart = new(AcceptConnections);
MainThread = new(threadStart);
if (OperatingSystem.IsWindows()) MainThread.SetApartmentState(ApartmentState.STA);
MainThread.Start();
ThreadStart threadStart = new(AcceptConnections);
MainThread = new(threadStart);
if (OperatingSystem.IsWindows()) MainThread.SetApartmentState(ApartmentState.STA);
MainThread.Start();
}
catch (Exception ex)
{
Debug.WriteLine("MsmhAgnosticServer Start: " + ex.Message);
}
}

private void Welcome()
Expand Down Expand Up @@ -156,18 +165,34 @@ await Task.Run(async () =>

private async void KillOnOverloadTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{
if (OperatingSystem.IsWindows() && typeof(PerformanceCounter) != null)
CpuUsage = await ProcessManager.GetCpuUsage(Environment.ProcessId, 1000);

if (CpuUsage >= Settings_.KillOnCpuUsage && Settings_.KillOnCpuUsage > 0)
try
{
KillAll();
}
if (OperatingSystem.IsWindows() && typeof(PerformanceCounter) != null)
CpuUsage = await ProcessManager.GetCpuUsage(Environment.ProcessId, 1000);

if (CpuUsage >= Settings_.KillOnCpuUsage && Settings_.KillOnCpuUsage > 0)
{
KillAll();
}

if (CpuUsage >= 75f)
{
try { Environment.Exit(0); } catch (Exception) { }
await ProcessManager.KillProcessByPidAsync(Environment.ProcessId);
}

if (CpuUsage >= 95f)
// Get Internet State
IPAddress ipToCheck = Settings_.BootstrapIpAddress;
if (ipToCheck == IPAddress.None || ipToCheck == IPAddress.Any || ipToCheck == IPAddress.IPv6None || ipToCheck == IPAddress.IPv6Any)
{
bool isIP = IPAddress.TryParse("8.8.8.8", out IPAddress? ip);
if (isIP && ip != null) ipToCheck = ip;
}
InternetState = await NetworkTool.GetInternetStateAsync(ipToCheck, 5000);
}
catch (Exception ex)
{
try { Environment.Exit(0); } catch (Exception) { }
await ProcessManager.KillProcessByPidAsync(Environment.ProcessId);
Debug.WriteLine("MsmhAgnosticServer KillOnOverloadTimer_Elapsed: " + ex.Message);
}
}

Expand Down Expand Up @@ -214,7 +239,6 @@ public void Stop()
KillAll();

MaxRequestsQueue.Clear();
DelinquentRequests.Clear();
TestRequests.Clear();

KillOnOverloadTimer.Stop();
Expand Down Expand Up @@ -542,7 +566,7 @@ private void ProxyTunnel_OnTunnelDisconnected(object? sender, EventArgs e)
pt.ClientSSL?.Disconnect();

TunnelManager_.Remove(pt);
Debug.WriteLine($"{pt.Req.Address} Disconnected");
//Debug.WriteLine($"{pt.Req.Address} Disconnected");
}
catch (Exception ex)
{
Expand Down
Loading

0 comments on commit edfb57c

Please sign in to comment.