Skip to content

Commit

Permalink
feat: 提供服务(未完成)
Browse files Browse the repository at this point in the history
  • Loading branch information
SALTWOOD committed Mar 9, 2024
1 parent 394aa69 commit b802af0
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 38 deletions.
39 changes: 17 additions & 22 deletions CSharp-OpenBMCLAPI/Modules/Cluster.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@
using Avro.IO;
using Downloader;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using SocketIOClient;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Policy;
using System.Security.Principal;
using System.Text;
Expand All @@ -27,7 +31,6 @@ public class Cluster : RunnableBase
public bool IsEnabled { get; private set; }
private Task? _keepAlive;
//List<Task> tasks = new List<Task>();
private HttpServer server;

public Cluster(ClusterInfo info, TokenManager token) : base()
{
Expand All @@ -52,7 +55,6 @@ public Cluster(ClusterInfo info, TokenManager token) : base()
}
});

this.server = new();
}

private void HandleError(SocketIOResponse resp)
Expand Down Expand Up @@ -82,7 +84,7 @@ protected async Task<int> AsyncRun()
await RequestCertification();
//t.Start();

InitializeHttpsServer();
InitializeService();

await Enable();

Expand All @@ -106,31 +108,24 @@ protected async Task<int> AsyncRun()
private void InitializeService()
{
var builder = WebApplication.CreateBuilder();
X509Certificate2 cert = X509Certificate2.CreateFromPemFile($"{SharedData.Config.clusterFileDirectory}certifications/cert.pem",
$"{SharedData.Config.clusterFileDirectory}certifications/key.pem");
builder.WebHost.UseUrls(new[]
{
//$"https://{SharedData.ClusterInfo.ClusterID}.openbmclapi.933.moe:4000/",
//$"https://localhost:4000/",
$"https://{SharedData.ClusterInfo.ClusterID}.openbmclapi.933.moe:4000/",
//$"https://localhost:4000/"
});
//builder.WebHost.UseKestrel(option => option.ConfigureHttpsDefaults(i => i.ServerCertificate = cert));
var app = builder.Build();
var path = $"{SharedData.Config.clusterFileDirectory}cache";
app.UseStaticFiles();
app.MapGet("/download", (context) => HttpServerUtils.DownloadHash(context));
app.MapGet("/measure", (context) => HttpServerUtils.Measure(context));
app.MapGet("/download/{hash}", (context) => HttpServerUtils.DownloadHash(context));
app.Map("/measure/{size}", (context) => HttpServerUtils.Measure(context));
var t = app.RunAsync();
}

/*
private void RequestFirewall()
{
FtpWebRequest requestDownload;
requestDownload = (FtpWebRequest)WebRequest.Create(uri);
requestDownload.UsePassive = false;
requestDownload.KeepAlive = false;
requestDownload.UseBinary = true;
requestDownload.Method = WebRequestMethods.Ftp.DownloadFile;
requestDownload.Credentials = new NetworkCredential(ftpInfoDownload[3], ftpInfoDownload[4]);
responseDownload = (FtpWebResponse)requestDownload.GetResponse();
Stream ftpStream = responseDownload.GetResponseStream();
}*/

public void Connect()
{
this.socket.ConnectAsync().Wait();
Expand Down
47 changes: 31 additions & 16 deletions CSharp-OpenBMCLAPI/Modules/HttpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,34 @@ namespace CSharpOpenBMCLAPI.Modules
{
public class HttpServerUtils
{
public static Task Measure(HttpContext context)
public static async Task Measure(HttpContext context)
{
var pairs = Utils.GetQueryStrings(context.Request.QueryString.Value);
bool valid = Utils.CheckSign(context.Request.Path.Value?.Split('/').LastOrDefault()
bool valid = Utils.CheckSign(context.Request.Path.Value
, SharedData.ClusterInfo.ClusterSecret
, pairs.GetValueOrDefault("s")
, pairs.GetValueOrDefault("e")
);
if (valid)
{
byte[] bytes = new byte[1024];
context.Response.StatusCode = 200;
byte[] buffer = new byte[1024];
for (int i = 0; i < Convert.ToInt32(context.Request.Path.Value?.Split('/').LastOrDefault()); i++)
{
for (int j = 0; j < 1024; j++)
{
context.Response.StatusCode = 200;
context.Response.Body.Write(bytes);
await context.Response.BodyWriter.WriteAsync(buffer);
}
}
}
else
{
context.Response.StatusCode = 403;
context.Response.Body.Write(Encoding.UTF8.GetBytes($"Access to \"{context.Request.Path}\" has been blocked due to your request timeout or invalidity."));
await context.Response.WriteAsync($"Access to \"{context.Request.Path}\" has been blocked due to your request timeout or invalidity.");
}

return Task.CompletedTask;
}

[HttpHandler("/download/")]
public static Task DownloadHash(HttpContext context)
public static async Task DownloadHash(HttpContext context)
{
var pairs = Utils.GetQueryStrings(context.Request.QueryString.Value);
string? hash = context.Request.Path.Value?.Split('/').LastOrDefault();
Expand All @@ -57,17 +54,23 @@ public static Task DownloadHash(HttpContext context)
{
if (range != null)
{
(int from, int to) = (Convert.ToInt32(range?.Split('-')[0]), Convert.ToInt32(range?.Split('-')[1]));
range = range.Replace("bytes=", "");
var rangeHeader = range?.Split('-');
(long from, long to) = ToRangeByte(rangeHeader);
using var file = File.OpenRead($"{SharedData.Config.clusterFileDirectory}cache/{hash[0..2]}/{hash}");
if (from == -1)
from = 0;
if (to == -1)
to = file.Length - 1;
file.Position = from;
byte[] buffer = new byte[to - from + 1];
file.Read(buffer, 0, to - from + 1);
file.Read(buffer, 0, (int)(to - from + 1));
context.Response.StatusCode = 206;
context.Response.Body.Write(buffer);
await context.Response.BodyWriter.WriteAsync(buffer);
}
else
{
context.Response.SendFileAsync($"{SharedData.Config.clusterFileDirectory}cache/{hash[0..2]}/{hash}").Wait();
await context.Response.SendFileAsync($"{SharedData.Config.clusterFileDirectory}cache/{hash[0..2]}/{hash}");
}
}
catch
Expand All @@ -78,10 +81,22 @@ public static Task DownloadHash(HttpContext context)
else
{
context.Response.StatusCode = 403;
context.Response.Body.Write(Encoding.UTF8.GetBytes($"Access to \"{context.Request.Path}\" has been blocked due to your request timeout or invalidity."));
await context.Response.WriteAsync($"Access to \"{context.Request.Path}\" has been blocked due to your request timeout or invalidity.");
}
}

return Task.CompletedTask;
private static (long from, long to) ToRangeByte(string[]? rangeHeader)
{
int from, to;
if (string.IsNullOrWhiteSpace(rangeHeader?.FirstOrDefault()))
from = -1;
else
from = Convert.ToInt32(rangeHeader?.FirstOrDefault());
if (string.IsNullOrWhiteSpace(rangeHeader?.LastOrDefault()))
to = -1;
else
to = Convert.ToInt32(rangeHeader?.LastOrDefault());
return (from, to);
}
}
}

0 comments on commit b802af0

Please sign in to comment.