65 lines
2.1 KiB
C#
65 lines
2.1 KiB
C#
using Microsoft.AspNetCore.HttpOverrides;
|
|
using VirtualDDNSRouter.Server.Interfaces;
|
|
using VirtualDDNSRouter.Server.Services;
|
|
using Route = VirtualDDNSRouter.Server.Models.Route;
|
|
|
|
|
|
var builder = WebApplication.CreateSlimBuilder(args);
|
|
|
|
builder.Services.AddSingleton<IYamlParser, YamlParser>();
|
|
|
|
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
|
builder.Services.AddOpenApi();
|
|
|
|
var app = builder.Build();
|
|
|
|
app.UseForwardedHeaders(new ForwardedHeadersOptions
|
|
{
|
|
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
|
|
ForwardedHeaders.XForwardedProto
|
|
});
|
|
|
|
if (app.Environment.IsDevelopment()) app.MapOpenApi();
|
|
|
|
var routes = new List<Route>();
|
|
|
|
app.MapGet("/setip/{path}/{port}/{apiKey}",
|
|
async (IYamlParser yamlParser, HttpContext context, string path, ushort port, string apiKey) =>
|
|
{
|
|
var rules = await yamlParser.GetRules();
|
|
app.Logger.LogInformation($"New setip request for {path} with port {port}.");
|
|
var ruleValid = rules.Any(r => r.path == path && r.apiKey == apiKey);
|
|
if (!ruleValid)
|
|
{
|
|
app.Logger.LogInformation($"Invalid rule for {path} with port {port}.");
|
|
return Results.StatusCode(StatusCodes.Status403Forbidden);
|
|
}
|
|
|
|
var clientIp = context.Connection.RemoteIpAddress;
|
|
if (clientIp is null)
|
|
{
|
|
app.Logger.LogInformation($"Could not get the client ip address for {path} with port {port}.");
|
|
return Results.BadRequest("Could not get the client ip address");
|
|
}
|
|
|
|
var existingRoute = routes.FirstOrDefault(r => r.path == path);
|
|
if (existingRoute is not null) routes.Remove(existingRoute);
|
|
|
|
routes.Add(new Route
|
|
{
|
|
ipAddress = clientIp,
|
|
path = path,
|
|
port = port
|
|
});
|
|
|
|
return Results.Ok($"goto/{path}");
|
|
});
|
|
|
|
app.MapGet("/goto/{path}", (string path) =>
|
|
{
|
|
var redirectRoute = routes.FirstOrDefault(r => r.path == path);
|
|
if (redirectRoute is null) return Task.FromResult(Results.NotFound());
|
|
return Task.FromResult(Results.Redirect($"http://{redirectRoute.ipAddress}:{redirectRoute.port}"));
|
|
});
|
|
|
|
app.Run(); |