Files
Flypaper/src/Flypaper.Core/Runtime/TrapRunner.cs
T
2026-11-15 19:05:21 +01:00

113 lines
3.8 KiB
C#

using System.Net;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Flypaper.Core.Networking;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Runtime;
public sealed partial class TrapRunner(
IConnectionGovernor governor,
ITrapStrategySelector strategies,
ITrapEventSink sink,
IOptionsMonitor<FlypaperOptions> options,
TimeProvider timeProvider,
ILogger<TrapRunner> logger)
{
public async Task<TrapOutcome> RunAsync(
TrapContext context,
Func<ITarpitStrategy, CancellationToken, ValueTask<ITrapChannel>> openChannel,
CancellationToken ct)
{
var session = context.Session;
var strategy = strategies.Select(context);
if (strategy is null || !governor.TryAcquire(session, out var lease))
{
Publish(context, strategy?.Name ?? "none", 0, TrapOutcome.Rejected);
return TrapOutcome.Rejected;
}
using var _ = lease;
var description = strategy is IStrategyDetails details ? details.Describe() : strategy.Name;
using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
CountingTrapChannel? channel = null;
var outcome = TrapOutcome.Completed;
try
{
channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
await strategy.RunAsync(channel, linked.Token);
}
catch (OperationCanceledException) when (linked.IsCancellationRequested)
{
outcome = hold.IsCancellationRequested && !ct.IsCancellationRequested
? TrapOutcome.Timeout
: TrapOutcome.ClientAborted;
}
catch (IOException)
{
outcome = TrapOutcome.ClientAborted;
}
Publish(context, description, channel?.BytesSent ?? 0, outcome);
return outcome;
}
private void Publish(TrapContext context, string strategy, long bytesSent, TrapOutcome outcome)
{
var session = context.Session;
var trapEvent = new TrapEvent(
session.Id,
session.Protocol,
session.RemoteIp,
strategy,
session.StartedAt,
timeProvider.GetUtcNow(),
bytesSent,
outcome,
context.Target,
context.ClientInfo);
var store = !(options.CurrentValue.IgnorePrivateNetworks && PrivateNetworks.Contains(trapEvent.RemoteIp));
var storageNote = store ? "" : " (not stored)";
if (outcome == TrapOutcome.Rejected)
{
LogRejected(trapEvent.RemoteIp, trapEvent.Target, trapEvent.ClientInfo, storageNote);
}
else
{
LogTrapped(
trapEvent.RemoteIp,
trapEvent.Target,
trapEvent.Duration.TotalSeconds,
trapEvent.BytesSent,
trapEvent.Outcome,
trapEvent.ClientInfo,
storageNote);
}
if (store)
{
sink.Publish(trapEvent);
}
}
[LoggerMessage(Level = LogLevel.Information,
Message = "Trapped {RemoteIp} {Target} {DurationSeconds:F1}s {BytesSent}B {Outcome} \"{UserAgent}\"{StorageNote}")]
private partial void LogTrapped(
IPAddress remoteIp,
string? target,
double durationSeconds,
long bytesSent,
TrapOutcome outcome,
string? userAgent,
string storageNote);
[LoggerMessage(Level = LogLevel.Information, Message = "Rejected {RemoteIp} {Target} \"{UserAgent}\"{StorageNote}")]
private partial void LogRejected(IPAddress remoteIp, string? target, string? userAgent, string storageNote);
}