68 lines
2.2 KiB
C#
68 lines
2.2 KiB
C#
using Microsoft.Extensions.Options;
|
|
|
|
namespace Flypaper.Core;
|
|
|
|
public sealed class TrapRunner(
|
|
IConnectionGovernor governor,
|
|
IEnumerable<ITarpitStrategy> strategies,
|
|
ITrapEventSink sink,
|
|
IOptions<FlypaperOptions> options,
|
|
TimeProvider timeProvider)
|
|
{
|
|
public async Task<TrapOutcome> RunAsync(
|
|
TrapContext context,
|
|
Func<CancellationToken, ValueTask<ITrapChannel>> openChannel,
|
|
CancellationToken ct)
|
|
{
|
|
var session = context.Session;
|
|
var strategy = strategies.FirstOrDefault(s => s.Supports(session.Protocol));
|
|
|
|
if (strategy is null || !governor.TryAcquire(session, out var lease))
|
|
{
|
|
Publish(context, strategy?.Name ?? "none", 0, TrapOutcome.Rejected);
|
|
return TrapOutcome.Rejected;
|
|
}
|
|
|
|
using var _ = lease;
|
|
using var hold = new CancellationTokenSource(options.Value.MaxHoldDuration, timeProvider);
|
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
|
|
|
|
CountingTrapChannel? channel = null;
|
|
var outcome = TrapOutcome.Completed;
|
|
try
|
|
{
|
|
channel = new CountingTrapChannel(await openChannel(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, strategy.Name, channel?.BytesSent ?? 0, outcome);
|
|
return outcome;
|
|
}
|
|
|
|
private void Publish(TrapContext context, string strategy, long bytesSent, TrapOutcome outcome)
|
|
{
|
|
var session = context.Session;
|
|
sink.Publish(new TrapEvent(
|
|
session.Id,
|
|
session.Protocol,
|
|
session.RemoteIp,
|
|
strategy,
|
|
session.StartedAt,
|
|
timeProvider.GetUtcNow(),
|
|
bytesSent,
|
|
outcome,
|
|
context.Target,
|
|
context.ClientInfo));
|
|
}
|
|
}
|