取消MVC功能

This commit is contained in:
老九 2021-09-11 22:02:54 +08:00
parent f7e71f598d
commit ee0003b73e
14 changed files with 66 additions and 191 deletions

View File

@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@ -48,7 +49,12 @@ namespace FastGithub.Dns
}
catch (Exception ex)
{
this.logger.LogError($"DNS服务启动失败{ex.Message}{Environment.NewLine}请配置系统或浏览器使用{nameof(FastGithub)}的DoHhttps://127.0.0.1/dns-query或向系统hosts文件添加github相关域名的ip为127.0.0.1");
var builder = new StringBuilder().AppendLine($"DNS服务启动失败({ex.Message}),你可以选择如下的一种操作:");
builder.AppendLine($"1. 关闭占用udp53端口的进程然后重新打开本程序");
builder.AppendLine($"2. 向系统hosts文件添加要加速的域名的ip为127.0.0.1");
builder.AppendLine($"3. 配置系统或浏览器使用DNS over HTTPShttps://127.0.0.1/dns-query");
builder.Append($"4. 在局域网其它设备上运行本程序然后将本机DNS设置为局域网设备的IP");
this.logger.LogError(builder.ToString());
}
foreach (var item in this.conflictValidators)

View File

@ -37,7 +37,7 @@ namespace FastGithub.DomainResolve
try
{
await this.dnscryptProxy.StartAsync(cancellationToken);
this.logger.LogInformation($"{this.dnscryptProxy}启动完成");
this.logger.LogInformation($"已监听端口{this.dnscryptProxy.LocalEndPoint?.Port}{this.dnscryptProxy}启动完成");
}
catch (Exception ex)
{

View File

@ -5,9 +5,9 @@ using Microsoft.Extensions.DependencyInjection;
namespace FastGithub
{
/// <summary>
/// https反向代理的中间件扩展
/// ApplicationBuilder扩展
/// </summary>
public static class ReverseProxyApplicationBuilderExtensions
public static class ApplicationBuilderExtensions
{
/// <summary>
/// 使用请求日志中间件
@ -28,7 +28,7 @@ namespace FastGithub
public static IApplicationBuilder UseReverseProxy(this IApplicationBuilder app)
{
var middleware = app.ApplicationServices.GetRequiredService<ReverseProxyMiddleware>();
return app.Use(next => context => middleware.InvokeAsync(context, next));
return app.Use(next => context => middleware.InvokeAsync(context));
}
}
}

View File

@ -16,30 +16,48 @@ namespace FastGithub
public static class KestrelServerOptionsExtensions
{
/// <summary>
/// 监听http的反向代理
/// 无限制
/// </summary>
/// <param name="kestrel"></param>
public static void ListenHttpReverseProxy(this KestrelServerOptions kestrel)
public static void NoLimit(this KestrelServerOptions kestrel)
{
const int HTTP_PORT = 80;
var logger = kestrel.GetLogger();
if (LocalMachine.CanListenTcp(HTTP_PORT) == false)
{
logger.LogWarning($"由于tcp端口{HTTP_PORT}已经被其它进程占用http反向代理功能将受限");
kestrel.Limits.MaxRequestBodySize = null;
}
else
/// <summary>
/// 监听ssh
/// </summary>
/// <param name="kestrel"></param>
public static void ListenSsh(this KestrelServerOptions kestrel)
{
kestrel.Listen(IPAddress.Any, HTTP_PORT);
logger.LogInformation($"已监听tcp端口{HTTP_PORT}http反向代理启动完成");
const int SSH_PORT = 22;
if (LocalMachine.CanListenTcp(SSH_PORT) == true)
{
kestrel.Listen(IPAddress.Any, SSH_PORT, listen => listen.UseConnectionHandler<GithubSshProxyHandler>());
kestrel.GetLogger().LogInformation($"已监听tcp端口{SSH_PORT}github的ssh代理启动完成");
}
}
/// <summary>
/// 监听https的反向代理
/// 监听http
/// </summary>
/// <param name="kestrel"></param>
public static void ListenHttpsReverseProxy(this KestrelServerOptions kestrel)
public static void ListenHttp(this KestrelServerOptions kestrel)
{
const int HTTP_PORT = 80;
if (LocalMachine.CanListenTcp(HTTP_PORT) == true)
{
kestrel.Listen(IPAddress.Any, HTTP_PORT);
kestrel.GetLogger().LogInformation($"已监听tcp端口{HTTP_PORT}http反向代理启动完成");
}
}
/// <summary>
/// 监听https
/// </summary>
/// <param name="kestrel"></param>
/// <exception cref="FastGithubException"></exception>
public static void ListenHttps(this KestrelServerOptions kestrel)
{
const int HTTPS_PORT = 443;
if (OperatingSystem.IsWindows())
@ -49,7 +67,7 @@ namespace FastGithub
if (LocalMachine.CanListenTcp(HTTPS_PORT) == false)
{
throw new FastGithubException($"由于tcp端口{HTTPS_PORT}已经被其它进程占用{nameof(FastGithub)}无法进行必须的https反向代理");
throw new FastGithubException($"tcp端口{HTTPS_PORT}已经被其它进程占用");
}
var certService = kestrel.ApplicationServices.GetRequiredService<CertService>();
@ -65,25 +83,6 @@ namespace FastGithub
logger.LogInformation($"已监听tcp端口{HTTPS_PORT}https反向代理启动完成");
}
/// <summary>
/// 监听github的ssh的代理
/// </summary>
/// <param name="kestrel"></param>
public static void ListenGithubSshProxy(this KestrelServerOptions kestrel)
{
const int SSH_PORT = 22;
var logger = kestrel.GetLogger();
if (LocalMachine.CanListenTcp(SSH_PORT) == false)
{
logger.LogWarning($"由于tcp端口{SSH_PORT}已经被其它进程占用github的ssh代理功能将受限");
}
else
{
kestrel.Listen(IPAddress.Any, SSH_PORT, listen => listen.UseConnectionHandler<GithubSshProxyHandler>());
logger.LogInformation($"已监听tcp端口{SSH_PORT}github的ssh代理启动完成");
}
}
/// <summary>
/// 获取日志

View File

@ -17,6 +17,7 @@ namespace FastGithub.ReverseProxy
private readonly IHttpClientFactory httpClientFactory;
private readonly FastGithubConfig fastGithubConfig;
private readonly ILogger<ReverseProxyMiddleware> logger;
private readonly DomainConfig defaultDomainConfig = new() { TlsSni = true };
public ReverseProxyMiddleware(
IHttpForwarder httpForwarder,
@ -34,16 +35,24 @@ namespace FastGithub.ReverseProxy
/// 处理请求
/// </summary>
/// <param name="context"></param>
/// <param name="next"></param>
/// <returns></returns>
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
public async Task InvokeAsync(HttpContext context)
{
var host = context.Request.Host.Host;
if (this.fastGithubConfig.TryGetDomainConfig(host, out var domainConfig) == false)
{
await next(context);
domainConfig = this.defaultDomainConfig;
}
else if (domainConfig.Response != null)
if (domainConfig.Response == null)
{
var scheme = context.Request.Scheme;
var destinationPrefix = GetDestinationPrefix(scheme, host, domainConfig.Destination);
var httpClient = this.httpClientFactory.CreateHttpClient(domainConfig);
var error = await httpForwarder.SendAsync(context, destinationPrefix, httpClient);
await HandleErrorAsync(context, error);
}
else
{
context.Response.StatusCode = domainConfig.Response.StatusCode;
context.Response.ContentType = domainConfig.Response.ContentType;
@ -52,14 +61,6 @@ namespace FastGithub.ReverseProxy
await context.Response.WriteAsync(domainConfig.Response.ContentValue);
}
}
else
{
var scheme = context.Request.Scheme;
var destinationPrefix = GetDestinationPrefix(scheme, host, domainConfig.Destination);
var httpClient = this.httpClientFactory.CreateHttpClient(domainConfig);
var error = await httpForwarder.SendAsync(context, destinationPrefix, httpClient);
await HandleErrorAsync(context, error);
}
}
/// <summary>
@ -91,13 +92,7 @@ namespace FastGithub.ReverseProxy
/// <returns></returns>
private static async Task HandleErrorAsync(HttpContext context, ForwarderError error)
{
if (error == ForwarderError.None)
{
return;
}
var errorFeature = context.GetForwarderErrorFeature();
if (errorFeature == null || context.Response.HasStarted)
if (error == ForwarderError.None || context.Response.HasStarted)
{
return;
}
@ -105,7 +100,7 @@ namespace FastGithub.ReverseProxy
await context.Response.WriteAsJsonAsync(new
{
error = error.ToString(),
message = errorFeature.Exception?.Message
message = context.GetForwarderErrorFeature()?.Exception?.Message
});
}
}

View File

@ -6,7 +6,7 @@ namespace FastGithub
/// <summary>
/// https反向代理的服务注册扩展
/// </summary>
public static class ReverseProxyServiceCollectionExtensions
public static class ServiceCollectionExtensions
{
/// <summary>
/// 添加https反向代理

View File

@ -1,25 +0,0 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace FastGithub.Controllers
{
/// <summary>
/// 证书控制器
/// </summary>
public class CertController : Controller
{
/// <summary>
/// 下载CA证书
/// </summary>
/// <returns></returns>
public async Task<IActionResult> Index()
{
var certFile = $"CACert/{nameof(FastGithub)}.cer";
this.Response.ContentType = "application/x-x509-ca-cert";
this.Response.Headers.Add("Content-Disposition", $"attachment;filename={nameof(FastGithub)}.cer");
await this.Response.SendFileAsync(certFile);
return new EmptyResult();
}
}
}

View File

@ -1,27 +0,0 @@
using FastGithub.Configuration;
using FastGithub.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace FastGithub.Controllers
{
/// <summary>
/// 首页控制器
/// </summary>
public class HomeController : Controller
{
/// <summary>
/// 首页
/// </summary>
/// <returns></returns>
public IActionResult Index()
{
var model = new Home
{
Version = ProductionVersion.Current?.ToString(),
ProjectUri = "https://github.com/dotnetcore/FastGithub"
};
return View(model);
}
}
}

View File

@ -1,18 +0,0 @@
namespace FastGithub.Models
{
/// <summary>
/// 首页模型
/// </summary>
public class Home
{
/// <summary>
/// 获取版本号
/// </summary>
public string? Version { get; set; }
/// <summary>
/// 请求域名或ip
/// </summary>
public string? ProjectUri { get; set; }
}
}

View File

@ -51,10 +51,10 @@ namespace FastGithub
webBuilder.UseShutdownTimeout(TimeSpan.FromSeconds(2d));
webBuilder.UseKestrel(kestrel =>
{
kestrel.Limits.MaxRequestBodySize = null;
kestrel.ListenHttpsReverseProxy();
kestrel.ListenHttpReverseProxy();
kestrel.ListenGithubSshProxy();
kestrel.NoLimit();
kestrel.ListenSsh();
kestrel.ListenHttp();
kestrel.ListenHttps();
});
webBuilder.UseSerilog((hosting, logger) =>
{

View File

@ -30,12 +30,10 @@ namespace FastGithub
services.Configure<FastGithubOptions>(this.Configuration.GetSection(nameof(FastGithub)));
services.AddConfiguration();
services.AddDnsServer();
services.AddDomainResolve();
services.AddDnsServer();
services.AddHttpClient();
services.AddReverseProxy();
services.AddControllersWithViews();
services.AddHostedService<VersonHostedService>();
}
@ -48,11 +46,6 @@ namespace FastGithub
app.UseRequestLogging();
app.UseDnsOverHttps();
app.UseReverseProxy();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
});
}
}
}

View File

@ -1,44 +0,0 @@

@{
Layout = null;
}
@model Home
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href=" https://cdn.jsdelivr.net/npm/@@bootcss/v3.bootcss.com@@1.0.10/dist/css/bootstrap.min.css">
<title>FastGithub</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>FastGithub</h1>
<p>github加速神器解决github打不开、用户头像无法加载、releases无法上传下载、git-clone、git-pull、git-push失败等问题</p>
<h3>软件信息</h3>
<p>
<span>安装版本:</span>
<span>v@(Model?.Version)</span>
</p>
<p>
<span>项目地址:</span>
<a target="_blank" href="@(Model?.ProjectUri)">@(Model?.ProjectUri)</a>
</p>
<h3>CA证书</h3>
<p>
你可能需要在客户端设备下载FastGithub自颁发的CA证书<a target="_blank" href="/cert">FastGithub.cer</a>,导入到受信任的根证书颁发机构或浏览器
</p>
</div>
</div>
</div>
</body>
</html>

View File

@ -1,3 +0,0 @@
@using FastGithub
@using FastGithub.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@ -1 +0,0 @@