diff --git a/docs/architecture.md b/docs/architecture.md
index c2578df5..1fce41c9 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -65,7 +65,7 @@ Relevant local RFC text is under `docs/standards/rfcs/`. For this client, start
`CacheListenerService` binds the configured TLS endpoints and admits connections up to `MaxActiveConnections`. Each admitted socket disables Nagle and receives its own send and receive buffer limits immediately after accept and before TLS. Listening-socket options are not inherited. A socket-option failure disposes that socket and releases the admission slot. The configured sizes are kernel buffer limits; the operating system may round them, and they are not a measured congestion window. Each admitted socket then gets one TLS 1.2 or 1.3 handshake with no client certificate and revocation checks off. The certificate lease is taken per connection and disposed with that connection. After the handshake succeeds, `NntpCacheListenerSession` uses `StreamCacheListenerTransport`. The session does not own the socket or the certificate. `IoProgressTimeout` is one no-progress deadline for each read and each non-empty write on that connection. Completing the call is progress, and the next call gets a new deadline. The session passes each logical buffer — the status line, the article image, and the terminating `.\r\n` — in its own write. It does not slice a buffer into 32 KiB pieces. `Stream.WriteAsync` accepts the supplied buffer or throws, so that deadline covers the whole buffer and is not reset mid-call. A transport that returns a shorter positive count has made progress: the session continues at the first unaccepted byte, and the next write gets a new deadline. Shutdown cancellation, handshake failure, timeout, I/O, and other connection failures use the same listener logs as before.
-The greeting is `201 NNTP Service Ready, posting prohibited` because posting is not implemented. It is sent before any command response. Command keywords are ASCII case-insensitive. One or more spaces or tabs separate the keyword from its argument. Lines end in CRLF. A command longer than 512 octets, including CRLF, is answered with `501 Syntax error` and is not split into a later command. Bytes after one command stay in the buffer. `QUIT` with no argument sends `205 Connection closing` and returns; the service then closes the connection. `QUIT` with an argument is `501` and the connection stays open. `DATE` with no argument sends `111` and fourteen UTC digits `yyyymmddhhmmss` from the same `TimeProvider` used for article admission, then waits for another command. `DATE` with an argument is `501` and the connection stays open. Any other command is `500 Unknown command`. A peer close ends the session without another response.
+The greeting is `201 NNTP Service Ready, posting prohibited` because posting is not implemented. It is sent before any command response. Command keywords are ASCII case-insensitive. One or more spaces or tabs separate the keyword from its argument. Lines end in CRLF. A command longer than 512 octets, including CRLF, is answered with `501 Syntax error` and is not split into a later command. Bytes after one command stay in the buffer. The command being handled stays at the front of that buffer until its response writes finish, so the session reads the line and the Message-ID from those bytes. The `220` and `111` lines are formatted into buffers owned by that session and are not overwritten until the write of that line has returned. `QUIT` with no argument sends `205 Connection closing` and returns; the service then closes the connection. `QUIT` with an argument is `501` and the connection stays open. `DATE` with no argument sends `111` and fourteen UTC digits `yyyymmddhhmmss` from the same `TimeProvider` used for article admission, then waits for another command. `DATE` with an argument is `501` and the connection stays open. Any other command is `500 Unknown command`. A peer close ends the session without another response.
`ARTICLE` with no argument, or with an all-digit article number, is `412 No newsgroup selected`. There is no selected group. Extra arguments, or a Message-ID that fails `NntpMessageIdValidation`, are `501 Syntax error`. That validator is the RFC 5536 grammar already used by article admission, so it is stricter than an opaque RFC 3977 message-id. A valid Message-ID that is not retained is `430 No Such Article Found`.
diff --git a/src/VectorNNTPD.BackFillerService/Listener/NntpCacheListenerSession.cs b/src/VectorNNTPD.BackFillerService/Listener/NntpCacheListenerSession.cs
index 3da0899e..1ade284a 100644
--- a/src/VectorNNTPD.BackFillerService/Listener/NntpCacheListenerSession.cs
+++ b/src/VectorNNTPD.BackFillerService/Listener/NntpCacheListenerSession.cs
@@ -88,12 +88,24 @@ internal sealed class NntpCacheListenerSession
///
private readonly TimeProvider _time;
- /// Unread command bytes, including any pipelined commands after the one just parsed.
+ /// Unread command bytes. The command being handled stays at the front until its response writes finish.
private byte[] _pending = new byte[MaximumCommandOctets];
/// Valid prefix length of .
private int _pendingCount;
+ ///
+ /// Reused 111 response. Twenty octets. The next DATE does not write it until the previous write has returned.
+ ///
+ private readonly byte[] _dateResponse = new byte[DatePrefix.Length + 14 + 2];
+
+ ///
+ /// Reused 220 response. Sized for the longest RFC 5536 message-id.
+ /// The next ARTICLE does not write it until the previous status write has returned.
+ ///
+ private readonly byte[] _articleFollows = new byte[
+ ArticlePrefix.Length + NntpMessageIdValidation.MaxMessageIdLength + ArticleFollowsSuffix.Length];
+
/// Initializes a session over an established transport.
/// Connected transport. Not disposed by this session.
/// Article owner. Claims are committed only after a complete article write.
@@ -129,49 +141,59 @@ internal async Task RunAsync(CancellationToken cancellationToken)
while (!cancellationToken.IsCancellationRequested)
{
var read = await ReadCommandAsync(cancellationToken).ConfigureAwait(false);
- if (read.Kind == CommandReadKind.Disconnected)
- {
- return;
- }
-
- if (read.Kind == CommandReadKind.Overlong)
+ try
{
- await WriteFullyAsync(SyntaxError, cancellationToken).ConfigureAwait(false);
- continue;
- }
+ if (read.Kind == CommandReadKind.Disconnected)
+ {
+ return;
+ }
- var line = read.Line;
- if (EqualsIgnoreCase(Keyword(line), QuitKeyword))
- {
- if (HasArgument(line))
+ if (read.Kind == CommandReadKind.Overlong)
{
await WriteFullyAsync(SyntaxError, cancellationToken).ConfigureAwait(false);
continue;
}
- await WriteFullyAsync(Closing, cancellationToken).ConfigureAwait(false);
- return;
- }
+ var line = read.Line;
+ if (EqualsIgnoreCase(Keyword(line), QuitKeyword))
+ {
+ if (HasArgument(line))
+ {
+ await WriteFullyAsync(SyntaxError, cancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ await WriteFullyAsync(Closing, cancellationToken).ConfigureAwait(false);
+ return;
+ }
- if (EqualsIgnoreCase(Keyword(line), DateKeyword))
- {
- if (HasArgument(line))
+ if (EqualsIgnoreCase(Keyword(line), DateKeyword))
{
- await WriteFullyAsync(SyntaxError, cancellationToken).ConfigureAwait(false);
+ if (HasArgument(line))
+ {
+ await WriteFullyAsync(SyntaxError, cancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ await WriteFullyAsync(BuildDateResponse(), cancellationToken).ConfigureAwait(false);
continue;
}
- await WriteFullyAsync(BuildDateResponse(), cancellationToken).ConfigureAwait(false);
- continue;
- }
+ if (!EqualsIgnoreCase(Keyword(line), ArticleKeyword))
+ {
+ await WriteFullyAsync(UnknownCommand, cancellationToken).ConfigureAwait(false);
+ continue;
+ }
- if (!EqualsIgnoreCase(Keyword(line), ArticleKeyword))
+ await HandleArticleAsync(line, cancellationToken).ConfigureAwait(false);
+ }
+ finally
{
- await WriteFullyAsync(UnknownCommand, cancellationToken).ConfigureAwait(false);
- continue;
+ if (read.Consumed > 0)
+ {
+ RemoveFront(read.Consumed);
+ }
}
-
- await HandleArticleAsync(line, cancellationToken).ConfigureAwait(false);
}
}
@@ -188,7 +210,7 @@ internal async Task RunAsync(CancellationToken cancellationToken)
///
private async Task HandleArticleAsync(ReadOnlyMemory line, CancellationToken cancellationToken)
{
- if (!TryReadSingleArgument(line.Span, out var argument))
+ if (!TryReadSingleArgument(line, out var argument))
{
await WriteFullyAsync(argument.IsEmpty ? NoNewsgroup : SyntaxError, cancellationToken).ConfigureAwait(false);
return;
@@ -244,6 +266,10 @@ private async Task HandleArticleAsync(ReadOnlyMemory line, CancellationTok
/// Reads one command, or reports that the peer closed or the line exceeded 512 octets.
/// Cancels the transport read.
/// The next command, an overlong marker, or disconnect.
+ ///
+ /// A command result refers to the front of and does not copy it.
+ /// The caller drops those bytes only after the handler has finished, including its response writes.
+ ///
private async Task ReadCommandAsync(CancellationToken cancellationToken)
{
while (true)
@@ -258,9 +284,7 @@ private async Task ReadCommandAsync(CancellationToken cancellationT
return CommandRead.Overlong();
}
- var line = _pending.AsMemory(0, crlf).ToArray();
- RemoveFront(lineLength);
- return CommandRead.Command(line);
+ return CommandRead.Command(_pending.AsMemory(0, crlf), lineLength);
}
if (_pendingCount >= MaximumCommandOctets)
@@ -414,43 +438,45 @@ private static bool HasArgument(ReadOnlyMemory line)
///
/// Reads the single argument of an ARTICLE command.
///
- /// Command line without CRLF.
+ /// Command line without CRLF. The argument is a slice of this memory.
///
/// The argument when there is exactly one. Empty when the argument is missing.
/// When extra arguments are present, is non-empty and the method returns false.
+ /// The memory is a slice of , not a copy.
///
///
/// when there is exactly one argument.
/// when the argument is missing or more than one argument is present.
///
- private static bool TryReadSingleArgument(ReadOnlySpan line, out ReadOnlyMemory argument)
+ private static bool TryReadSingleArgument(ReadOnlyMemory line, out ReadOnlyMemory argument)
{
- var index = KeywordLength(line);
- while (index < line.Length && line[index] is (byte)' ' or (byte)'\t')
+ var span = line.Span;
+ var index = KeywordLength(span);
+ while (index < span.Length && span[index] is (byte)' ' or (byte)'\t')
{
index++;
}
- if (index >= line.Length)
+ if (index >= span.Length)
{
argument = ReadOnlyMemory.Empty;
return false;
}
var start = index;
- while (index < line.Length && line[index] is not (byte)' ' and not (byte)'\t')
+ while (index < span.Length && span[index] is not (byte)' ' and not (byte)'\t')
{
index++;
}
var end = index;
- while (index < line.Length && line[index] is (byte)' ' or (byte)'\t')
+ while (index < span.Length && span[index] is (byte)' ' or (byte)'\t')
{
index++;
}
- argument = line[start..end].ToArray();
- return index >= line.Length;
+ argument = line.Slice(start, end - start);
+ return index >= span.Length;
}
/// Counts the keyword octets at the start of .
@@ -520,22 +546,22 @@ private static bool EqualsIgnoreCase(ReadOnlySpan value, ReadOnlySpan111 yyyymmddhhmmss from , in UTC, ending in CRLF.
/// Seconds are the clock's whole seconds. The response has no subsecond field.
///
- /// Twenty octets: the status, fourteen digits, and CRLF.
- private byte[] BuildDateResponse()
+ /// Twenty octets in : the status, fourteen digits, and CRLF.
+ /// The returned memory stays valid until the next DATE on this session, which waits for the write to finish.
+ private ReadOnlyMemory BuildDateResponse()
{
var utc = _time.GetUtcNow().UtcDateTime;
- var line = new byte[DatePrefix.Length + 14 + 2];
- DatePrefix.CopyTo(line);
- var digits = line.AsSpan(DatePrefix.Length, 14);
+ DatePrefix.CopyTo(_dateResponse);
+ var digits = _dateResponse.AsSpan(DatePrefix.Length, 14);
WriteDigits(digits[..4], utc.Year);
WriteDigits(digits.Slice(4, 2), utc.Month);
WriteDigits(digits.Slice(6, 2), utc.Day);
WriteDigits(digits.Slice(8, 2), utc.Hour);
WriteDigits(digits.Slice(10, 2), utc.Minute);
WriteDigits(digits.Slice(12, 2), utc.Second);
- line[^2] = (byte)'\r';
- line[^1] = (byte)'\n';
- return line;
+ _dateResponse[^2] = (byte)'\r';
+ _dateResponse[^1] = (byte)'\n';
+ return _dateResponse;
}
/// Writes as ASCII digits into , most significant digit first.
@@ -550,28 +576,34 @@ private static void WriteDigits(Span destination, int value)
}
}
- /// Builds 220 0 <message-id> article follows ending in CRLF.
- /// Message-ID octets from the command. Not rewritten.
- /// The status line, including CRLF.
- private static byte[] BuildFollowsLine(ReadOnlySpan messageId)
+ /// Writes 220 0 <message-id> article follows ending in CRLF into .
+ /// Message-ID octets from the command. Not rewritten. At most octets.
+ /// The status line, including CRLF. Valid until the next successful ARTICLE on this session.
+ private ReadOnlyMemory BuildFollowsLine(ReadOnlySpan messageId)
{
- var line = new byte[ArticlePrefix.Length + messageId.Length + ArticleFollowsSuffix.Length];
- ArticlePrefix.CopyTo(line);
- messageId.CopyTo(line.AsSpan(ArticlePrefix.Length));
- ArticleFollowsSuffix.CopyTo(line.AsSpan(ArticlePrefix.Length + messageId.Length));
- return line;
+ ArgumentOutOfRangeException.ThrowIfGreaterThan(messageId.Length, NntpMessageIdValidation.MaxMessageIdLength);
+ var length = ArticlePrefix.Length + messageId.Length + ArticleFollowsSuffix.Length;
+ ArticlePrefix.CopyTo(_articleFollows);
+ messageId.CopyTo(_articleFollows.AsSpan(ArticlePrefix.Length));
+ ArticleFollowsSuffix.CopyTo(_articleFollows.AsSpan(ArticlePrefix.Length + messageId.Length));
+ return _articleFollows.AsMemory(0, length);
}
/// One read from the command buffer.
private readonly struct CommandRead
{
- /// Stores a classified read. is null unless is a command.
+ /// Stores a classified read.
/// Whether a command, an overlong line, or disconnect was observed.
- /// Command bytes without CRLF, or null.
- private CommandRead(CommandReadKind kind, byte[]? line)
+ /// Command bytes without CRLF. Empty unless is a command.
+ ///
+ /// Bytes at the front of the pending buffer that the caller drops after the handler finishes.
+ /// Zero when this read already discarded its line or has no line.
+ ///
+ private CommandRead(CommandReadKind kind, ReadOnlyMemory line, int consumed)
{
Kind = kind;
Line = line;
+ Consumed = consumed;
}
/// Whether a complete command, an overlong discard, or peer close was read from the buffer.
@@ -580,24 +612,34 @@ private CommandRead(CommandReadKind kind, byte[]? line)
/// Command octets without CRLF when is ; otherwise empty.
internal ReadOnlyMemory Line { get; }
- /// Creates a parsed command.
- /// Command bytes without CRLF.
+ /// Pending-buffer prefix the caller removes after this line is no longer used, including its CRLF.
+ internal int Consumed { get; }
+
+ /// Creates a parsed command that still occupies the front of the pending buffer.
+ /// Command bytes without CRLF. A slice of the pending buffer.
+ /// Line length including CRLF.
/// A command read.
- internal static CommandRead Command(byte[] line) => new(CommandReadKind.Command, line);
+ internal static CommandRead Command(ReadOnlyMemory line, int consumed) =>
+ new(CommandReadKind.Command, line, consumed);
- /// Creates an overlong-line result.
+ /// Creates an overlong-line result whose bytes were already discarded.
/// A read that must be answered with 501 and not interpreted.
- internal static CommandRead Overlong() => new(CommandReadKind.Overlong, null);
+ internal static CommandRead Overlong() => new(CommandReadKind.Overlong, ReadOnlyMemory.Empty, 0);
/// Creates a disconnect result.
/// A read that ends the session without a further response.
- internal static CommandRead Disconnected() => new(CommandReadKind.Disconnected, null);
+ internal static CommandRead Disconnected() => new(CommandReadKind.Disconnected, ReadOnlyMemory.Empty, 0);
}
/// Classification of one command-buffer read.
private enum CommandReadKind : byte
{
- /// A CRLF-terminated command of at most 512 octets was copied out of the buffer.
+ ///
+ /// A CRLF-terminated command of at most 512 octets. The line references the session pending buffer and is not a copy.
+ ///
+ ///
+ /// Do not retain or use that memory after the pending buffer is consumed, compacted, resized, or reused.
+ ///
Command = 0,
/// The line exceeded 512 octets and was discarded through its CRLF.
diff --git a/tests/VectorNNTPD.BackFillerService.Tests/Listener/NntpCacheListenerSessionTests.cs b/tests/VectorNNTPD.BackFillerService.Tests/Listener/NntpCacheListenerSessionTests.cs
index 29959652..f472a591 100644
--- a/tests/VectorNNTPD.BackFillerService.Tests/Listener/NntpCacheListenerSessionTests.cs
+++ b/tests/VectorNNTPD.BackFillerService.Tests/Listener/NntpCacheListenerSessionTests.cs
@@ -692,6 +692,44 @@ public async Task A_retry_after_rollback_fails_once_ttl_has_expired()
Assert.Equal(0, authority.RetainedCount);
}
+ ///
+ /// A command split before its LF, then a later command, still produces the exact status lines after the pending buffer is reused.
+ ///
+ [Fact]
+ public async Task A_command_split_before_lf_is_followed_by_the_next_command()
+ {
+ var time = new ManualTimeProvider(DateTimeOffset.Parse("2026-03-04T05:06:07Z"));
+ await using var authority = ArticleRetentionAuthorityTests.Create(time, 1_000_000);
+ var prepared = RetentionTestArticles.RetainPrepared(authority, "");
+ var articleWireLength = Greeting.Length + Status("").Length + prepared.ArtData.Length + Terminator.Length;
+ var written = await RunAsync(authority, "ARTICLE \r\nDATE\r\nQUIT\r\n", maxRead: 14, time: time);
+
+ AssertArticleWire(written.AsSpan(0, articleWireLength).ToArray(), "", prepared.ArtData);
+ Assert.Equal(
+ "111 20260304050607\r\n205 Connection closing\r\n"u8.ToArray(),
+ written.AsSpan(articleWireLength).ToArray());
+ Assert.Equal(0, authority.RetainedCount);
+ }
+
+ /// Successive DATE commands rewrite the session response and keep each timestamp.
+ [Fact]
+ public async Task Successive_date_commands_keep_each_timestamp()
+ {
+ var time = new SteppingTimeProvider(
+ DateTimeOffset.Parse("2026-03-04T05:06:07Z"),
+ DateTimeOffset.Parse("2026-12-31T23:59:58Z"));
+ await using var authority = ArticleRetentionAuthorityTests.Create(new ManualTimeProvider(DateTimeOffset.Parse("2026-01-01T00:00:00Z")), 1_000_000);
+ var written = await RunAsync(authority, "DATE\r\nDATE\r\nQUIT\r\n", time: time);
+
+ Assert.Equal(
+ Greeting.ToArray()
+ .Concat("111 20260304050607\r\n"u8.ToArray())
+ .Concat("111 20261231235958\r\n"u8.ToArray())
+ .Concat("205 Connection closing\r\n"u8.ToArray())
+ .ToArray(),
+ written);
+ }
+
///
/// DATE returns RFC 3977 111 yyyymmddhhmmss from the retention clock and does not claim an article.
///
@@ -1187,6 +1225,28 @@ private static int IndexOf(byte[] buffer, byte[] pattern)
return -1;
}
+ /// Returns a different UTC instant from each call, in order.
+ private sealed class SteppingTimeProvider : TimeProvider
+ {
+ private readonly DateTimeOffset[] _instants;
+ private int _index;
+
+ /// Stores the instants returned by successive clock reads.
+ /// At least one instant. Later reads repeat the last instant.
+ internal SteppingTimeProvider(params DateTimeOffset[] instants)
+ {
+ _instants = instants;
+ }
+
+ ///
+ public override DateTimeOffset GetUtcNow()
+ {
+ var instant = _instants[Math.Min(_index, _instants.Length - 1)];
+ _index++;
+ return instant;
+ }
+ }
+
///
/// ICacheListenerTransport double with scripted read chunking and failing/blocking writes.
///