Files
VDR/VirtualDDNSRouter.Server/Program.cs

62 lines
2.0 KiB
C#

using System.Collections.Concurrent;
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 ConcurrentDictionary<string, 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");
}
routes[path] = new Route
{
ipAddress = clientIp,
path = path,
port = port
};
return Results.Ok($"goto/{path}");
});
app.MapGet("/goto/{path}", (string path) =>
{
if (routes.TryGetValue(path, out var route)) return Results.Redirect($"http://{route.ipAddress}:{route.port}");
return Results.NotFound();
});
app.Run();