Elisa/Elisa.WebAPI/ProxyControl.cs

63 lines
2.0 KiB
C#

using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Titanium.Web.Proxy;
using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy.Models;
namespace Elisa.WebAPI;
public class ProxyControl
{
private static readonly Regex HostFilter = new Regex("(.*).(girlfrontline\\.co\\.kr|ppgame\\.com|txwy\\.tw|sunborngame\\.com|aihelp.net.cn).*");
private readonly string forwardIpAddress;
private readonly ProxyServer proxyServer;
private readonly ExplicitProxyEndPoint explicitEndPoint;
public ProxyControl(string forwardIpAddress, int port = 8888)
{
this.forwardIpAddress = forwardIpAddress;
proxyServer = new ProxyServer();
explicitEndPoint = new ExplicitProxyEndPoint(System.Net.IPAddress.Any, port, true);
proxyServer.BeforeRequest += OnRequest;
}
public void Start()
{
proxyServer.AddEndPoint(explicitEndPoint);
proxyServer.Start();
proxyServer.SetAsSystemHttpProxy(explicitEndPoint);
proxyServer.SetAsSystemHttpsProxy(explicitEndPoint);
}
public void Stop()
{
proxyServer.BeforeRequest -= OnRequest;
proxyServer.Stop();
}
private async Task OnRequest(object sender, SessionEventArgs e)
{
var requestUri = e.HttpClient.Request.RequestUri;
if (HostFilter.IsMatch(requestUri.Host))
{
//Log the request and where its forwarding to
Serilog.Log.Information("Forwarding request for {RequestUri} to {ForwardIpAddress}", requestUri, forwardIpAddress);
//Build an entirely new URI with the specified IP address
var newUri = new Uri("http://" + forwardIpAddress + requestUri.PathAndQuery, UriKind.Absolute);
Serilog.Log.Information("Forwarded request to {requestUri}", newUri);
e.HttpClient.Request.RequestUri = newUri;
//Bubble it out to user
}
}
}