Make the hold method configurable in the dashboard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9a56fc5b48
commit
6b9bf3cd5f
40 files changed
+815
-134
No files matched your search
@@ -0,0 +1,8 @@
|
||||
namespace Flypaper.Core.Abstractions;
|
||||
|
||||
public interface IStrategyDetails
|
||||
{
|
||||
string MediaType { get; }
|
||||
|
||||
string Describe();
|
||||
}
|
||||
@@ -19,7 +19,8 @@ public static class FlypaperCoreExtensions
|
||||
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
||||
services.TryAddSingleton<IRandomSource, SystemRandomSource>();
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
|
||||
services.TryAddSingleton<ITrapStrategySelector, ProtocolStrategySelector>();
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, TextDripStrategy>());
|
||||
services.TryAddSingleton<ITrapStrategySelector, ConfiguredStrategySelector>();
|
||||
services.TryAddSingleton<TrapRunner>();
|
||||
services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core.Runtime;
|
||||
|
||||
public sealed class ConfiguredStrategySelector(
|
||||
IEnumerable<ITarpitStrategy> strategies,
|
||||
IOptionsMonitor<DripOptions> options,
|
||||
IRandomSource random) : ITrapStrategySelector
|
||||
{
|
||||
public ITarpitStrategy? Select(TrapContext context)
|
||||
{
|
||||
var candidates = strategies.Where(strategy => strategy.Supports(context.Session.Protocol)).ToList();
|
||||
string[] wanted = options.CurrentValue.Content switch
|
||||
{
|
||||
DripContent.Text => [TextDripStrategy.StrategyName],
|
||||
DripContent.Alternating => [HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName],
|
||||
_ => [HtmlDripStrategy.StrategyName]
|
||||
};
|
||||
|
||||
var matching = candidates.Where(strategy => wanted.Contains(strategy.Name)).ToList();
|
||||
return matching.Count == 0
|
||||
? candidates.FirstOrDefault()
|
||||
: matching[random.Next(0, matching.Count)];
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
|
||||
namespace Flypaper.Core.Runtime;
|
||||
|
||||
public sealed class ProtocolStrategySelector(IEnumerable<ITarpitStrategy> strategies) : ITrapStrategySelector
|
||||
{
|
||||
public ITarpitStrategy? Select(TrapContext context) =>
|
||||
strategies.FirstOrDefault(strategy => strategy.Supports(context.Session.Protocol));
|
||||
}
|
||||
@@ -17,7 +17,7 @@ public sealed partial class TrapRunner(
|
||||
{
|
||||
public async Task<TrapOutcome> RunAsync(
|
||||
TrapContext context,
|
||||
Func<CancellationToken, ValueTask<ITrapChannel>> openChannel,
|
||||
Func<ITarpitStrategy, CancellationToken, ValueTask<ITrapChannel>> openChannel,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var session = context.Session;
|
||||
@@ -30,6 +30,7 @@ public sealed partial class TrapRunner(
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -37,7 +38,7 @@ public sealed partial class TrapRunner(
|
||||
var outcome = TrapOutcome.Completed;
|
||||
try
|
||||
{
|
||||
channel = new CountingTrapChannel(await openChannel(linked.Token));
|
||||
channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
|
||||
await strategy.RunAsync(channel, linked.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (linked.IsCancellationRequested)
|
||||
@@ -51,7 +52,7 @@ public sealed partial class TrapRunner(
|
||||
outcome = TrapOutcome.ClientAborted;
|
||||
}
|
||||
|
||||
Publish(context, strategy.Name, channel?.BytesSent ?? 0, outcome);
|
||||
Publish(context, description, channel?.BytesSent ?? 0, outcome);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Globalization;
|
||||
using Flypaper.Core.Strategies;
|
||||
|
||||
namespace Flypaper.Core.Settings;
|
||||
|
||||
public sealed record HoldMethodSettings(
|
||||
DripContent Content,
|
||||
TimeSpan MinDelay,
|
||||
TimeSpan MaxDelay,
|
||||
int MinChunkSize,
|
||||
int MaxChunkSize,
|
||||
TimeSpan MaxHoldDuration)
|
||||
{
|
||||
public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize);
|
||||
|
||||
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
|
||||
{
|
||||
[SettingKeys.DripContent] = Content.ToString(),
|
||||
[SettingKeys.DripMinDelay] = MinDelay.ToString("c", CultureInfo.InvariantCulture),
|
||||
[SettingKeys.DripMaxDelay] = MaxDelay.ToString("c", CultureInfo.InvariantCulture),
|
||||
[SettingKeys.DripMinChunkSize] = MinChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.DripMaxChunkSize] = MaxChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
|
||||
};
|
||||
|
||||
public static double AverageBytesPerSecond(TimeSpan minDelay, TimeSpan maxDelay, int minChunkSize, int maxChunkSize)
|
||||
{
|
||||
var averageDelay = (minDelay + maxDelay).TotalSeconds / 2;
|
||||
return averageDelay <= 0 ? 0 : (minChunkSize + maxChunkSize) / 2d / averageDelay;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record HoldMethodInput(
|
||||
string? Content,
|
||||
string? MinDelayMs,
|
||||
string? MaxDelayMs,
|
||||
string? MinChunkSize,
|
||||
string? MaxChunkSize,
|
||||
string? MaxHoldDuration);
|
||||
|
||||
public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors);
|
||||
@@ -5,7 +5,6 @@ namespace Flypaper.Core.Settings;
|
||||
public sealed record RuntimeSettings(
|
||||
int MaxConnections,
|
||||
int MaxConnectionsPerIp,
|
||||
TimeSpan MaxHoldDuration,
|
||||
int RetentionDays,
|
||||
bool IgnorePrivateNetworks)
|
||||
{
|
||||
@@ -13,7 +12,6 @@ public sealed record RuntimeSettings(
|
||||
{
|
||||
[SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
||||
[SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false"
|
||||
};
|
||||
|
||||
@@ -3,6 +3,5 @@ namespace Flypaper.Core.Settings;
|
||||
public sealed record RuntimeSettingsInput(
|
||||
string? MaxConnections,
|
||||
string? MaxConnectionsPerIp,
|
||||
string? MaxHoldDuration,
|
||||
string? RetentionDays,
|
||||
bool IgnorePrivateNetworks);
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Globalization;
|
||||
using Flypaper.Core.Strategies;
|
||||
|
||||
namespace Flypaper.Core.Settings;
|
||||
|
||||
@@ -9,12 +10,14 @@ public static class RuntimeSettingsParser
|
||||
|
||||
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
|
||||
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
|
||||
private const int MinDelayMs = 10;
|
||||
private const int MaxDelayMs = 30_000;
|
||||
private const int MaxChunkSize = 4096;
|
||||
|
||||
public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
|
||||
{
|
||||
var errors = new Dictionary<string, string>();
|
||||
|
||||
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
|
||||
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors);
|
||||
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, errors);
|
||||
var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors);
|
||||
@@ -33,12 +36,55 @@ public static class RuntimeSettingsParser
|
||||
var settings = new RuntimeSettings(
|
||||
maxConnections!.Value,
|
||||
perIp!.Value,
|
||||
hold!.Value,
|
||||
retention!.Value,
|
||||
input.IgnorePrivateNetworks);
|
||||
return new RuntimeSettingsParseResult(settings, errors);
|
||||
}
|
||||
|
||||
public static HoldMethodParseResult ParseHoldMethod(HoldMethodInput input)
|
||||
{
|
||||
var errors = new Dictionary<string, string>();
|
||||
|
||||
DripContent? content = Enum.TryParse<DripContent>(input.Content, ignoreCase: true, out var parsed) && Enum.IsDefined(parsed)
|
||||
? parsed
|
||||
: null;
|
||||
if (content is null)
|
||||
{
|
||||
errors[nameof(input.Content)] = "Bitte eine Methode wählen.";
|
||||
}
|
||||
|
||||
var minDelay = ParseInt(input.MinDelayMs, nameof(input.MinDelayMs), MinDelayMs, MaxDelayMs, errors);
|
||||
var maxDelay = ParseInt(input.MaxDelayMs, nameof(input.MaxDelayMs), MinDelayMs, MaxDelayMs, errors);
|
||||
var minChunk = ParseInt(input.MinChunkSize, nameof(input.MinChunkSize), 1, MaxChunkSize, errors);
|
||||
var maxChunk = ParseInt(input.MaxChunkSize, nameof(input.MaxChunkSize), 1, MaxChunkSize, errors);
|
||||
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
|
||||
|
||||
if (minDelay > maxDelay)
|
||||
{
|
||||
errors[nameof(input.MaxDelayMs)] = "Darf nicht kleiner sein als das Minimum.";
|
||||
}
|
||||
|
||||
if (minChunk > maxChunk)
|
||||
{
|
||||
errors[nameof(input.MaxChunkSize)] = "Darf nicht kleiner sein als das Minimum.";
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
return new HoldMethodParseResult(null, errors);
|
||||
}
|
||||
|
||||
return new HoldMethodParseResult(
|
||||
new HoldMethodSettings(
|
||||
content!.Value,
|
||||
TimeSpan.FromMilliseconds(minDelay!.Value),
|
||||
TimeSpan.FromMilliseconds(maxDelay!.Value),
|
||||
minChunk!.Value,
|
||||
maxChunk!.Value,
|
||||
hold!.Value),
|
||||
errors);
|
||||
}
|
||||
|
||||
private static TimeSpan? ParseTimeSpan(
|
||||
string? raw,
|
||||
string field,
|
||||
|
||||
@@ -7,13 +7,18 @@ public static class SettingKeys
|
||||
public const string MaxHoldDuration = "Flypaper:MaxHoldDuration";
|
||||
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
|
||||
public const string RetentionDays = "Flypaper:Retention:Days";
|
||||
public const string DripContent = "Flypaper:Drip:Content";
|
||||
public const string DripMinDelay = "Flypaper:Drip:MinDelay";
|
||||
public const string DripMaxDelay = "Flypaper:Drip:MaxDelay";
|
||||
public const string DripMinChunkSize = "Flypaper:Drip:MinChunkSize";
|
||||
public const string DripMaxChunkSize = "Flypaper:Drip:MaxChunkSize";
|
||||
|
||||
public static readonly IReadOnlySet<string> All = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
MaxConnections,
|
||||
MaxConnectionsPerIp,
|
||||
MaxHoldDuration,
|
||||
IgnorePrivateNetworks,
|
||||
RetentionDays
|
||||
};
|
||||
public static readonly IReadOnlyList<string> General =
|
||||
[MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
|
||||
|
||||
public static readonly IReadOnlyList<string> HoldMethod =
|
||||
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, MaxHoldDuration];
|
||||
|
||||
public static readonly IReadOnlySet<string> All =
|
||||
new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public enum DripContent
|
||||
{
|
||||
Html,
|
||||
Text,
|
||||
Alternating
|
||||
}
|
||||
@@ -4,6 +4,8 @@ public sealed class DripOptions
|
||||
{
|
||||
public const string SectionName = "Flypaper:Drip";
|
||||
|
||||
public DripContent Content { get; set; } = DripContent.Html;
|
||||
|
||||
public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50);
|
||||
|
||||
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(1);
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Globalization;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public abstract class DripStrategy(
|
||||
IOptionsMonitor<DripOptions> options,
|
||||
IRandomSource random,
|
||||
TimeProvider timeProvider) : ITarpitStrategy, IStrategyDetails
|
||||
{
|
||||
public abstract string Name { get; }
|
||||
|
||||
public abstract string MediaType { get; }
|
||||
|
||||
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
|
||||
|
||||
public string Describe()
|
||||
{
|
||||
var current = options.CurrentValue;
|
||||
return string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"{Name} {current.MinDelay.TotalMilliseconds:0}-{current.MaxDelay.TotalMilliseconds:0}ms {current.MinChunkSize}-{current.MaxChunkSize}B");
|
||||
}
|
||||
|
||||
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
|
||||
{
|
||||
foreach (var step in DripSchedule.Create(Content(random), random, options.CurrentValue))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await channel.WriteAsync(step.Chunk, ct);
|
||||
await Task.Delay(step.Delay, timeProvider, ct);
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract IEnumerable<string> Content(IRandomSource random);
|
||||
}
|
||||
@@ -14,24 +14,6 @@ public static class HtmlContent
|
||||
a { color: #0b5cad; }
|
||||
""";
|
||||
|
||||
private static readonly string[] Vocabulary =
|
||||
[
|
||||
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod",
|
||||
"tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim",
|
||||
"veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea",
|
||||
"commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", "esse",
|
||||
"cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident",
|
||||
"sunt", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", "praesent",
|
||||
"luctus", "vitae", "semper", "facilisis", "integer", "nec", "odio", "mauris", "massa", "vestibulum",
|
||||
"lacinia", "arcu", "eget", "nunc", "tristique", "fermentum", "pellentesque", "habitant", "morbi",
|
||||
"senectus", "netus", "malesuada", "fames", "turpis", "egestas", "porttitor", "rhoncus", "dapibus",
|
||||
"ornare", "sapien", "volutpat", "blandit", "aliquam", "etiam", "erat", "velit", "scelerisque",
|
||||
"viverra", "orci", "sagittis", "eu", "tellus", "cras", "pulvinar", "mattis", "pharetra", "convallis",
|
||||
"posuere", "morbi", "leo", "urna", "molestie", "at", "elementum", "sodales", "neque", "gravida",
|
||||
"dictum", "fusce", "ultrices", "placerat", "euismod", "quam", "suspendisse", "potenti", "nullam",
|
||||
"accumsan", "tincidunt", "varius", "sollicitudin", "imperdiet", "hendrerit", "bibendum", "cursus"
|
||||
];
|
||||
|
||||
private static readonly string[] Sections =
|
||||
["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files", "guides", "kb", "releases"];
|
||||
|
||||
@@ -78,7 +60,7 @@ public static class HtmlContent
|
||||
var count = random.Next(3, 7);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{Capitalize(Pick(random, Vocabulary))}</a>\n");
|
||||
builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{LoremText.Capitalize(LoremText.Word(random))}</a>\n");
|
||||
}
|
||||
|
||||
return builder.Append("</nav>\n").ToString();
|
||||
@@ -145,8 +127,8 @@ public static class HtmlContent
|
||||
continue;
|
||||
}
|
||||
|
||||
var word = Pick(random, Vocabulary);
|
||||
builder.Append(i == 0 ? Capitalize(word) : word);
|
||||
var word = LoremText.Word(random);
|
||||
builder.Append(i == 0 ? LoremText.Capitalize(word) : word);
|
||||
}
|
||||
|
||||
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
|
||||
@@ -154,17 +136,13 @@ public static class HtmlContent
|
||||
|
||||
private static string Link(IRandomSource random, int words)
|
||||
{
|
||||
var text = Phrase(random, words);
|
||||
var text = LoremText.Phrase(random, words);
|
||||
var slug = text.Replace(' ', '-');
|
||||
return $"<a href=\"/{Pick(random, Sections)}/{slug}\">{text}</a>";
|
||||
}
|
||||
|
||||
private static string Title(IRandomSource random, int min, int max) => Capitalize(Phrase(random, random.Next(min, max + 1)));
|
||||
|
||||
private static string Phrase(IRandomSource random, int count) =>
|
||||
string.Join(' ', Enumerable.Range(0, count).Select(_ => Pick(random, Vocabulary)));
|
||||
private static string Title(IRandomSource random, int min, int max) => LoremText.Capitalize(LoremText.Phrase(random, random.Next(min, max + 1)));
|
||||
|
||||
private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)];
|
||||
|
||||
private static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..];
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
@@ -7,19 +6,13 @@ namespace Flypaper.Core.Strategies;
|
||||
public sealed class HtmlDripStrategy(
|
||||
IOptionsMonitor<DripOptions> options,
|
||||
IRandomSource random,
|
||||
TimeProvider timeProvider) : ITarpitStrategy
|
||||
TimeProvider timeProvider) : DripStrategy(options, random, timeProvider)
|
||||
{
|
||||
public string Name => "html-drip";
|
||||
public const string StrategyName = "html-drip";
|
||||
|
||||
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
|
||||
public override string Name => StrategyName;
|
||||
|
||||
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
|
||||
{
|
||||
foreach (var step in DripSchedule.Create(HtmlContent.Generate(random), random, options.CurrentValue))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await channel.WriteAsync(step.Chunk, ct);
|
||||
await Task.Delay(step.Delay, timeProvider, ct);
|
||||
}
|
||||
}
|
||||
public override string MediaType => "text/html; charset=utf-8";
|
||||
|
||||
protected override IEnumerable<string> Content(IRandomSource random) => HtmlContent.Generate(random);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Text;
|
||||
using Flypaper.Core.Abstractions;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
internal static class LoremText
|
||||
{
|
||||
private static readonly string[] Vocabulary =
|
||||
[
|
||||
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod",
|
||||
"tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim",
|
||||
"veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea",
|
||||
"commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", "esse",
|
||||
"cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident",
|
||||
"sunt", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", "praesent",
|
||||
"luctus", "vitae", "semper", "facilisis", "integer", "nec", "odio", "mauris", "massa", "vestibulum",
|
||||
"lacinia", "arcu", "eget", "nunc", "tristique", "fermentum", "pellentesque", "habitant", "morbi",
|
||||
"senectus", "netus", "malesuada", "fames", "turpis", "egestas", "porttitor", "rhoncus", "dapibus",
|
||||
"ornare", "sapien", "volutpat", "blandit", "aliquam", "etiam", "erat", "velit", "scelerisque",
|
||||
"viverra", "orci", "sagittis", "eu", "tellus", "cras", "pulvinar", "mattis", "pharetra", "convallis",
|
||||
"posuere", "morbi", "leo", "urna", "molestie", "at", "elementum", "sodales", "neque", "gravida",
|
||||
"dictum", "fusce", "ultrices", "placerat", "euismod", "quam", "suspendisse", "potenti", "nullam",
|
||||
"accumsan", "tincidunt", "varius", "sollicitudin", "imperdiet", "hendrerit", "bibendum", "cursus"
|
||||
];
|
||||
|
||||
public static string Word(IRandomSource random) => Vocabulary[random.Next(0, Vocabulary.Length)];
|
||||
|
||||
public static string Phrase(IRandomSource random, int count) =>
|
||||
string.Join(' ', Enumerable.Range(0, count).Select(_ => Word(random)));
|
||||
|
||||
public static string Sentence(IRandomSource random)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
var words = random.Next(4, 21);
|
||||
for (var i = 0; i < words; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
builder.Append(i > 2 && random.Next(0, 9) == 0 ? ", " : " ");
|
||||
}
|
||||
|
||||
var word = Word(random);
|
||||
builder.Append(i == 0 ? Capitalize(word) : word);
|
||||
}
|
||||
|
||||
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
|
||||
}
|
||||
|
||||
public static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Text;
|
||||
using Flypaper.Core.Abstractions;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public static class TextContent
|
||||
{
|
||||
public static IEnumerable<string> Generate(IRandomSource random)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
var sentences = random.Next(1, 7);
|
||||
for (var i = 0; i < sentences; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
builder.Append(' ');
|
||||
}
|
||||
|
||||
builder.Append(LoremText.Sentence(random));
|
||||
}
|
||||
|
||||
yield return builder.Append(random.Next(0, 4) == 0 ? "\n\n" : "\n").ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public sealed class TextDripStrategy(
|
||||
IOptionsMonitor<DripOptions> options,
|
||||
IRandomSource random,
|
||||
TimeProvider timeProvider) : DripStrategy(options, random, timeProvider)
|
||||
{
|
||||
public const string StrategyName = "text-drip";
|
||||
|
||||
public override string Name => StrategyName;
|
||||
|
||||
public override string MediaType => "text/plain; charset=utf-8";
|
||||
|
||||
protected override IEnumerable<string> Content(IRandomSource random) => TextContent.Generate(random);
|
||||
}
|
||||
@@ -39,7 +39,7 @@ internal sealed class FlypaperMiddleware(
|
||||
|
||||
var outcome = await runner.RunAsync(
|
||||
trapContext,
|
||||
ct => OpenChannelAsync(context, session, ct),
|
||||
(strategy, ct) => OpenChannelAsync(context, session, strategy, ct),
|
||||
context.RequestAborted);
|
||||
|
||||
if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted)
|
||||
@@ -59,6 +59,7 @@ internal sealed class FlypaperMiddleware(
|
||||
private static async ValueTask<ITrapChannel> OpenChannelAsync(
|
||||
HttpContext context,
|
||||
TrapSession session,
|
||||
ITarpitStrategy strategy,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var minDataRate = context.Features.Get<IHttpMinResponseDataRateFeature>();
|
||||
@@ -71,7 +72,7 @@ internal sealed class FlypaperMiddleware(
|
||||
|
||||
var response = context.Response;
|
||||
response.StatusCode = StatusCodes.Status200OK;
|
||||
response.ContentType = "text/html; charset=utf-8";
|
||||
response.ContentType = strategy is IStrategyDetails details ? details.MediaType : "text/html; charset=utf-8";
|
||||
response.Headers.CacheControl = "no-store";
|
||||
response.Headers["X-Accel-Buffering"] = "no";
|
||||
await response.StartAsync(ct);
|
||||
|
||||
@@ -166,6 +166,7 @@ public sealed class CatchQueries(IDbContextFactory<FlypaperDbContext> dbContextF
|
||||
e.DurationMs / 1000d,
|
||||
e.BytesSent,
|
||||
e.Outcome,
|
||||
e.Strategy,
|
||||
e.RemoteIp,
|
||||
e.CountryCode,
|
||||
e.Country,
|
||||
|
||||
@@ -9,6 +9,7 @@ public sealed record CatchRecord(
|
||||
double DurationSeconds,
|
||||
long BytesSent,
|
||||
TrapOutcome Outcome,
|
||||
string Strategy,
|
||||
string Ip,
|
||||
string? CountryCode,
|
||||
string? Country,
|
||||
|
||||
@@ -12,33 +12,42 @@ public sealed partial class RuntimeSettingsStore(
|
||||
{
|
||||
private static readonly string[] RuntimeKeys = SettingKeys.All.ToArray();
|
||||
|
||||
public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default)
|
||||
public Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default) =>
|
||||
SaveValuesAsync(settings.ToConfiguration(), ct);
|
||||
|
||||
public Task SaveAsync(HoldMethodSettings settings, CancellationToken ct = default) =>
|
||||
SaveValuesAsync(settings.ToConfiguration(), ct);
|
||||
|
||||
public async Task ResetAsync(IReadOnlyCollection<string>? keys = null, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
await RuntimeSettings(db, keys).ExecuteDeleteAsync(ct);
|
||||
Reload();
|
||||
}
|
||||
|
||||
public async Task<bool> HasOverridesAsync(IReadOnlyCollection<string>? keys = null, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
return await RuntimeSettings(db, keys).AnyAsync(ct);
|
||||
}
|
||||
|
||||
private async Task SaveValuesAsync(IReadOnlyDictionary<string, string> values, CancellationToken ct)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
await using var transaction = await db.Database.BeginTransactionAsync(ct);
|
||||
await RuntimeSettings(db).ExecuteDeleteAsync(ct);
|
||||
db.Settings.AddRange(settings.ToConfiguration().Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
|
||||
await RuntimeSettings(db, values.Keys.ToArray()).ExecuteDeleteAsync(ct);
|
||||
db.Settings.AddRange(values.Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
Reload();
|
||||
}
|
||||
|
||||
public async Task ResetAsync(CancellationToken ct = default)
|
||||
private static IQueryable<SettingEntity> RuntimeSettings(FlypaperDbContext db, IReadOnlyCollection<string>? keys = null)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
await RuntimeSettings(db).ExecuteDeleteAsync(ct);
|
||||
Reload();
|
||||
var selected = keys?.Where(key => SettingKeys.All.Contains(key)).ToArray() ?? RuntimeKeys;
|
||||
return db.Settings.Where(setting => selected.Contains(setting.Key));
|
||||
}
|
||||
|
||||
public async Task<bool> HasOverridesAsync(CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
return await RuntimeSettings(db).AnyAsync(ct);
|
||||
}
|
||||
|
||||
private static IQueryable<SettingEntity> RuntimeSettings(FlypaperDbContext db) =>
|
||||
db.Settings.Where(setting => RuntimeKeys.Contains(setting.Key));
|
||||
|
||||
private void Reload()
|
||||
{
|
||||
if (!source.TryReload())
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace Flypaper.Web.Components.Pages.Settings;
|
||||
|
||||
public sealed class HoldMethodModel
|
||||
{
|
||||
public string? Content { get; set; }
|
||||
|
||||
public string? MinDelayMs { get; set; }
|
||||
|
||||
public string? MaxDelayMs { get; set; }
|
||||
|
||||
public string? MinChunkSize { get; set; }
|
||||
|
||||
public string? MaxChunkSize { get; set; }
|
||||
|
||||
public string? MaxHoldDuration { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
@using System.Globalization
|
||||
@using Flypaper.Core
|
||||
@using Flypaper.Core.Settings
|
||||
@using Flypaper.Core.Strategies
|
||||
@using Flypaper.Storage.Settings
|
||||
@using Microsoft.Extensions.Options
|
||||
@inject IOptionsMonitor<DripOptions> Drip
|
||||
@inject IOptionsMonitor<FlypaperOptions> Core
|
||||
@inject RuntimeSettingsStore Store
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<section class="card form" id="hold-method">
|
||||
<header class="section-head">
|
||||
<h2>Haltemethode</h2>
|
||||
@if (_hasOverrides)
|
||||
{
|
||||
<span class="badge">Überschrieben</span>
|
||||
}
|
||||
</header>
|
||||
|
||||
@if (Saved == "saved")
|
||||
{
|
||||
<div class="banner ok">Gespeichert. Gilt ab dem nächsten Fang.</div>
|
||||
}
|
||||
else if (Saved == "reset")
|
||||
{
|
||||
<div class="banner ok">Haltemethode auf Standard zurückgesetzt.</div>
|
||||
}
|
||||
|
||||
<EditForm Model="Model" FormName="hold-method" OnSubmit="SaveAsync" action="/settings" class="form">
|
||||
<label for="drip-content">Inhalt</label>
|
||||
<InputSelect id="drip-content" @bind-Value="Model!.Content">
|
||||
<option value="@DripContent.Html">HTML-Fülltext</option>
|
||||
<option value="@DripContent.Text">Zufallstext (plain text)</option>
|
||||
<option value="@DripContent.Alternating">Wechselnd (pro Fang zufällig)</option>
|
||||
</InputSelect>
|
||||
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.Content)" />
|
||||
|
||||
<div class="grid">
|
||||
<div>
|
||||
<label for="drip-min-delay">Pause min. <span class="muted">(ms)</span></label>
|
||||
<InputText id="drip-min-delay" @bind-Value="Model!.MinDelayMs" class="mono" inputmode="numeric" data-bandwidth-input />
|
||||
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.MinDelayMs)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="drip-max-delay">Pause max. <span class="muted">(ms)</span></label>
|
||||
<InputText id="drip-max-delay" @bind-Value="Model!.MaxDelayMs" class="mono" inputmode="numeric" data-bandwidth-input />
|
||||
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.MaxDelayMs)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="drip-min-chunk">Paket min. <span class="muted">(Bytes)</span></label>
|
||||
<InputText id="drip-min-chunk" @bind-Value="Model!.MinChunkSize" class="mono" inputmode="numeric" data-bandwidth-input />
|
||||
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.MinChunkSize)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="drip-max-chunk">Paket max. <span class="muted">(Bytes)</span></label>
|
||||
<InputText id="drip-max-chunk" @bind-Value="Model!.MaxChunkSize" class="mono" inputmode="numeric" data-bandwidth-input />
|
||||
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.MaxChunkSize)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="hold">Maximale Haltedauer <span class="muted">(hh:mm:ss)</span></label>
|
||||
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(HoldMethodModel.MaxHoldDuration)" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="muted">
|
||||
Pause 10 ms bis 30 s, Paket 1 bis 4096 Bytes. Ø ca. <strong id="drip-bandwidth">@Bandwidth</strong> Bytes/s pro gefangener Verbindung.
|
||||
</p>
|
||||
|
||||
<div class="actions">
|
||||
<button type="submit">Speichern</button>
|
||||
</div>
|
||||
</EditForm>
|
||||
|
||||
<EditForm Model="_resetModel" FormName="hold-method-reset" OnSubmit="ResetAsync" action="/settings" class="danger-zone">
|
||||
<div class="actions">
|
||||
<button type="submit" class="secondary" disabled="@(!_hasOverrides)" onclick="return confirm('Haltemethode auf Standard zurücksetzen?')">Auf Standard zurücksetzen</button>
|
||||
</div>
|
||||
</EditForm>
|
||||
</section>
|
||||
|
||||
<script src="@Assets["settings.js"]" defer></script>
|
||||
|
||||
@code {
|
||||
private readonly object _resetModel = new();
|
||||
private IReadOnlyDictionary<string, string> _errors = new Dictionary<string, string>();
|
||||
private bool _hasOverrides;
|
||||
|
||||
[SupplyParameterFromForm(FormName = "hold-method")] private HoldMethodModel? Model { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "hold")] private string? Saved { get; set; }
|
||||
|
||||
private string Bandwidth
|
||||
{
|
||||
get
|
||||
{
|
||||
var ok = int.TryParse(Model?.MinDelayMs, out var minDelay) & int.TryParse(Model?.MaxDelayMs, out var maxDelay)
|
||||
& int.TryParse(Model?.MinChunkSize, out var minChunk) & int.TryParse(Model?.MaxChunkSize, out var maxChunk);
|
||||
if (!ok)
|
||||
{
|
||||
return "–";
|
||||
}
|
||||
|
||||
var bytesPerSecond = HoldMethodSettings.AverageBytesPerSecond(
|
||||
TimeSpan.FromMilliseconds(minDelay), TimeSpan.FromMilliseconds(maxDelay), minChunk, maxChunk);
|
||||
return bytesPerSecond.ToString(bytesPerSecond < 10 ? "0.0" : "N0", CultureInfo.GetCultureInfo("de-DE"));
|
||||
}
|
||||
}
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
Model ??= CurrentValues();
|
||||
_hasOverrides = await Store.HasOverridesAsync(SettingKeys.HoldMethod.ToArray());
|
||||
}
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
var result = RuntimeSettingsParser.ParseHoldMethod(new HoldMethodInput(
|
||||
Model!.Content,
|
||||
Model.MinDelayMs,
|
||||
Model.MaxDelayMs,
|
||||
Model.MinChunkSize,
|
||||
Model.MaxChunkSize,
|
||||
Model.MaxHoldDuration));
|
||||
|
||||
if (result.Settings is null)
|
||||
{
|
||||
_errors = result.Errors;
|
||||
return;
|
||||
}
|
||||
|
||||
await Store.SaveAsync(result.Settings);
|
||||
Navigation.NavigateTo("/settings?hold=saved#hold-method");
|
||||
}
|
||||
|
||||
private async Task ResetAsync()
|
||||
{
|
||||
await Store.ResetAsync(SettingKeys.HoldMethod.ToArray());
|
||||
Navigation.NavigateTo("/settings?hold=reset#hold-method");
|
||||
}
|
||||
|
||||
private HoldMethodModel CurrentValues()
|
||||
{
|
||||
var drip = Drip.CurrentValue;
|
||||
return new HoldMethodModel
|
||||
{
|
||||
Content = drip.Content.ToString(),
|
||||
MinDelayMs = ((int)drip.MinDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
|
||||
MaxDelayMs = ((int)drip.MaxDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
|
||||
MinChunkSize = drip.MinChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||
MaxChunkSize = drip.MaxChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,6 @@ public sealed class SettingsModel
|
||||
|
||||
public string? MaxConnectionsPerIp { get; set; }
|
||||
|
||||
public string? MaxHoldDuration { get; set; }
|
||||
|
||||
public string? RetentionDays { get; set; }
|
||||
|
||||
public bool IgnorePrivateNetworks { get; set; }
|
||||
|
||||
@@ -35,15 +35,12 @@ else if (Saved == "reset")
|
||||
<div class="banner ok">Auf Standard zurückgesetzt.</div>
|
||||
}
|
||||
|
||||
<HoldMethodSection />
|
||||
|
||||
<EditForm Model="Model" FormName="settings" OnSubmit="Save" action="/settings" class="card form">
|
||||
<h2>Anpassbar</h2>
|
||||
<h2>Allgemein</h2>
|
||||
|
||||
<div class="grid">
|
||||
<div>
|
||||
<label for="hold">Maximale Haltedauer <span class="muted">(hh:mm:ss)</span></label>
|
||||
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxHoldDuration)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="max">Max. Verbindungen gesamt</label>
|
||||
<InputText id="max" @bind-Value="Model!.MaxConnections" class="mono" />
|
||||
@@ -121,7 +118,6 @@ else if (Saved == "reset")
|
||||
var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput(
|
||||
Model!.MaxConnections,
|
||||
Model.MaxConnectionsPerIp,
|
||||
Model.MaxHoldDuration,
|
||||
Model.RetentionDays,
|
||||
Model.IgnorePrivateNetworks));
|
||||
|
||||
@@ -146,7 +142,6 @@ else if (Saved == "reset")
|
||||
var core = Core.CurrentValue;
|
||||
return new SettingsModel
|
||||
{
|
||||
MaxHoldDuration = core.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
||||
MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture),
|
||||
MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
|
||||
RetentionDays = Retention.CurrentValue.Days.ToString(CultureInfo.InvariantCulture),
|
||||
|
||||
@@ -169,6 +169,7 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
|
||||
Round(record.DurationSeconds),
|
||||
record.BytesSent,
|
||||
record.Outcome.ToString(),
|
||||
record.Strategy,
|
||||
record.Ip,
|
||||
record.CountryCode,
|
||||
CountryNames.Display(record.CountryCode, record.Country),
|
||||
|
||||
@@ -7,6 +7,7 @@ public sealed record CatchItem(
|
||||
double DurationSeconds,
|
||||
long BytesSent,
|
||||
string Outcome,
|
||||
string Strategy,
|
||||
string Ip,
|
||||
string? CountryCode,
|
||||
string? Country,
|
||||
|
||||
@@ -636,3 +636,23 @@ button.danger {
|
||||
overflow-wrap: anywhere;
|
||||
user-select: all;
|
||||
}
|
||||
|
||||
.section-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.section-head h2 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
select {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
(() => {
|
||||
const value = id => Number.parseInt(document.getElementById(id)?.value ?? "", 10);
|
||||
const output = document.getElementById("drip-bandwidth");
|
||||
if (!output) {
|
||||
return;
|
||||
}
|
||||
|
||||
const update = () => {
|
||||
const minDelay = value("drip-min-delay");
|
||||
const maxDelay = value("drip-max-delay");
|
||||
const minChunk = value("drip-min-chunk");
|
||||
const maxChunk = value("drip-max-chunk");
|
||||
const averageDelay = (minDelay + maxDelay) / 2000;
|
||||
const bytesPerSecond = (minChunk + maxChunk) / 2 / averageDelay;
|
||||
output.textContent = Number.isFinite(bytesPerSecond) && bytesPerSecond > 0
|
||||
? bytesPerSecond.toLocaleString("de-DE", { maximumFractionDigits: bytesPerSecond < 10 ? 1 : 0 })
|
||||
: "–";
|
||||
};
|
||||
|
||||
for (const input of document.querySelectorAll("[data-bandwidth-input]")) {
|
||||
input.addEventListener("input", update);
|
||||
}
|
||||
})();
|
||||
Reference in new issue
Block a user