The Italian pack can now produce and check the e-invoice and talk to the SDI: - FatturaPaWriter writes FPR12/FPA12 v1.2 with SDI file naming; FatturaPaValidator checks it against an embedded schema and the AdE semantic rules (official codes). - SdiReceiptReader reads RC, NS, MC, NE, DT, AT, MT and SE notifications. - The incoming-invoice model becomes the shared EInvoice* model, read and written. - In-house ImapClient and MimeParser (no external libraries) back the PEC channel; SdICoop (SOAP/MTOM with client certificate) and two generic REST intermediaries sit behind the same IEInvoiceTransport contract, with fake-server tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
478 lines
17 KiB
C#
478 lines
17 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Globalization;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace Khaemhat.Infrastructure.Tests.Mail;
|
|
|
|
/// <summary>A message held by <see cref="FakeImapServer"/>.</summary>
|
|
internal sealed class FakeImapMessage(long uid, byte[] content)
|
|
{
|
|
public long Uid { get; } = uid;
|
|
|
|
public byte[] Content { get; } = content;
|
|
|
|
public HashSet<string> Flags { get; } = new(StringComparer.OrdinalIgnoreCase);
|
|
}
|
|
|
|
/// <summary>
|
|
/// An IMAP server on the loopback interface, enough for the tests of the client and of the PEC channel: CAPABILITY,
|
|
/// LOGIN (quoted or literal), SELECT, UID SEARCH (ALL, UNSEEN, FROM, SINCE ignored), UID FETCH, UID STORE, UID MOVE,
|
|
/// UID COPY (NO [TRYCREATE] for a missing folder), CREATE, EXPUNGE, UID EXPUNGE, LOGOUT. One connection at a time.
|
|
/// </summary>
|
|
internal sealed partial class FakeImapServer : IAsyncDisposable
|
|
{
|
|
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
|
|
private readonly CancellationTokenSource _stop = new();
|
|
private readonly Task _loop;
|
|
private long _nextUid = 100;
|
|
|
|
public FakeImapServer(string user, string password, params byte[][] messages)
|
|
{
|
|
User = user;
|
|
Password = password;
|
|
Mailboxes["INBOX"] = [.. messages.Select(m => new FakeImapMessage(_nextUid++, m))];
|
|
_listener.Start();
|
|
_loop = Task.Run(AcceptAsync);
|
|
}
|
|
|
|
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
|
|
|
|
public string User { get; }
|
|
|
|
public string Password { get; }
|
|
|
|
/// <summary>Whether MOVE and UIDPLUS are announced.</summary>
|
|
public bool SupportsMove { get; init; } = true;
|
|
|
|
public ConcurrentDictionary<string, List<FakeImapMessage>> Mailboxes { get; } = new(StringComparer.OrdinalIgnoreCase);
|
|
|
|
public ConcurrentQueue<string> Commands { get; } = new();
|
|
|
|
public void Add(byte[] message) => Mailboxes["INBOX"].Add(new FakeImapMessage(_nextUid++, message));
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await _stop.CancelAsync();
|
|
_listener.Stop();
|
|
try
|
|
{
|
|
await _loop;
|
|
}
|
|
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
|
{
|
|
}
|
|
|
|
_stop.Dispose();
|
|
}
|
|
|
|
private async Task AcceptAsync()
|
|
{
|
|
while (!_stop.IsCancellationRequested)
|
|
{
|
|
TcpClient client;
|
|
try
|
|
{
|
|
client = await _listener.AcceptTcpClientAsync(_stop.Token);
|
|
}
|
|
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
|
{
|
|
return;
|
|
}
|
|
|
|
using (client)
|
|
{
|
|
try
|
|
{
|
|
await ServeAsync(client.GetStream());
|
|
}
|
|
catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException)
|
|
{
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task ServeAsync(NetworkStream stream)
|
|
{
|
|
var reader = new LineReader(stream);
|
|
async Task Send(string text) => await stream.WriteAsync(Encoding.ASCII.GetBytes(text + "\r\n"), _stop.Token);
|
|
await Send("* OK Fake IMAP ready");
|
|
var authenticated = false;
|
|
List<FakeImapMessage>? selected = null;
|
|
while (true)
|
|
{
|
|
var (line, literals) = await reader.CommandAsync(() => Send("+ go ahead"), _stop.Token);
|
|
if (line is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
Commands.Enqueue(line);
|
|
var space = line.IndexOf(' ', StringComparison.Ordinal);
|
|
var tag = line[..space];
|
|
var rest = line[(space + 1)..];
|
|
var verb = rest.Split(' ')[0].ToUpperInvariant();
|
|
if (verb == "UID")
|
|
{
|
|
verb = "UID " + rest.Split(' ')[1].ToUpperInvariant();
|
|
}
|
|
|
|
switch (verb)
|
|
{
|
|
case "CAPABILITY":
|
|
await Send("* CAPABILITY IMAP4rev1" + (SupportsMove ? " MOVE UIDPLUS" : string.Empty));
|
|
await Send(tag + " OK CAPABILITY completed");
|
|
break;
|
|
case "LOGIN":
|
|
var values = Arguments(rest[6..], literals);
|
|
authenticated = values.Count == 2 && values[0] == User && values[1] == Password;
|
|
await Send(tag + (authenticated ? " OK LOGIN completed" : " NO [AUTHENTICATIONFAILED] Invalid credentials"));
|
|
break;
|
|
case "SELECT" when authenticated:
|
|
var name = Arguments(rest[7..], literals)[0];
|
|
selected = Mailboxes.GetValueOrDefault(name);
|
|
await Send(selected is null ? tag + " NO Mailbox does not exist" : $"* {selected.Count} EXISTS");
|
|
if (selected is not null)
|
|
{
|
|
await Send(tag + " OK [READ-WRITE] SELECT completed");
|
|
}
|
|
|
|
break;
|
|
case "UID SEARCH" when selected is not null:
|
|
var criteria = rest[11..];
|
|
var found = selected.Where(m =>
|
|
(!criteria.Contains("UNSEEN", StringComparison.OrdinalIgnoreCase) || !m.Flags.Contains(@"\Seen"))
|
|
&& !m.Flags.Contains(@"\Deleted")
|
|
&& (FromPattern().Match(criteria) is not { Success: true } from
|
|
|| Encoding.Latin1.GetString(m.Content).Contains(from.Groups["v"].Value, StringComparison.OrdinalIgnoreCase)));
|
|
await Send("* SEARCH " + string.Join(' ', found.Select(m => m.Uid.ToString(CultureInfo.InvariantCulture))));
|
|
await Send(tag + " OK SEARCH completed");
|
|
break;
|
|
case "UID FETCH" when selected is not null:
|
|
var fetchUid = long.Parse(rest.Split(' ')[2], CultureInfo.InvariantCulture);
|
|
var message = selected.FirstOrDefault(m => m.Uid == fetchUid);
|
|
if (message is not null)
|
|
{
|
|
var index = selected.IndexOf(message) + 1;
|
|
await stream.WriteAsync(Encoding.ASCII.GetBytes($"* {index} FETCH (UID {message.Uid} BODY[] {{{message.Content.Length}}}\r\n"), _stop.Token);
|
|
await stream.WriteAsync(message.Content, _stop.Token);
|
|
await Send(")");
|
|
}
|
|
|
|
await Send(tag + " OK FETCH completed");
|
|
break;
|
|
case "UID STORE" when selected is not null:
|
|
var storeUid = long.Parse(rest.Split(' ')[2], CultureInfo.InvariantCulture);
|
|
var flags = rest[(rest.IndexOf('(', StringComparison.Ordinal) + 1)..rest.LastIndexOf(')')];
|
|
foreach (var m in selected.Where(m => m.Uid == storeUid))
|
|
{
|
|
m.Flags.UnionWith(flags.Split(' ', StringSplitOptions.RemoveEmptyEntries));
|
|
}
|
|
|
|
await Send(tag + " OK STORE completed");
|
|
break;
|
|
case "UID MOVE" or "UID COPY" when selected is not null:
|
|
var parts = rest.Split(' ', 4);
|
|
var uid = long.Parse(parts[2], CultureInfo.InvariantCulture);
|
|
var target = Arguments(parts[3], literals)[0];
|
|
if (!Mailboxes.TryGetValue(target, out var targetBox))
|
|
{
|
|
await Send(tag + " NO [TRYCREATE] Mailbox does not exist");
|
|
break;
|
|
}
|
|
|
|
foreach (var m in selected.Where(m => m.Uid == uid).ToList())
|
|
{
|
|
targetBox.Add(new FakeImapMessage(_nextUid++, m.Content));
|
|
if (verb == "UID MOVE")
|
|
{
|
|
selected.Remove(m);
|
|
}
|
|
}
|
|
|
|
await Send(tag + " OK done");
|
|
break;
|
|
case "CREATE" when authenticated:
|
|
Mailboxes.TryAdd(Arguments(rest[7..], literals)[0], []);
|
|
await Send(tag + " OK CREATE completed");
|
|
break;
|
|
case "EXPUNGE" or "UID EXPUNGE" when selected is not null:
|
|
selected.RemoveAll(m => m.Flags.Contains(@"\Deleted"));
|
|
await Send(tag + " OK EXPUNGE completed");
|
|
break;
|
|
case "LOGOUT":
|
|
await Send("* BYE Logging out");
|
|
await Send(tag + " OK LOGOUT completed");
|
|
return;
|
|
default:
|
|
await Send(tag + " BAD Unknown or not allowed: " + verb);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// The arguments: quoted strings, atoms, and {n} literals taken in order.
|
|
private static List<string> Arguments(string text, Queue<byte[]> literals)
|
|
{
|
|
var values = new List<string>();
|
|
var i = 0;
|
|
while (i < text.Length)
|
|
{
|
|
if (text[i] == ' ')
|
|
{
|
|
i++;
|
|
}
|
|
else if (text[i] == '"')
|
|
{
|
|
var value = new StringBuilder();
|
|
i++;
|
|
while (i < text.Length && text[i] != '"')
|
|
{
|
|
if (text[i] == '\\')
|
|
{
|
|
i++;
|
|
}
|
|
|
|
value.Append(text[i]);
|
|
i++;
|
|
}
|
|
|
|
values.Add(value.ToString());
|
|
i++;
|
|
}
|
|
else if (text[i] == '{')
|
|
{
|
|
values.Add(Encoding.UTF8.GetString(literals.Dequeue()));
|
|
i = text.IndexOf('}', i) + 1;
|
|
}
|
|
else
|
|
{
|
|
var end = text.IndexOf(' ', i);
|
|
values.Add(end < 0 ? text[i..] : text[i..end]);
|
|
i = end < 0 ? text.Length : end;
|
|
}
|
|
}
|
|
|
|
return values;
|
|
}
|
|
|
|
[GeneratedRegex("FROM \"(?<v>[^\"]*)\"", RegexOptions.IgnoreCase)]
|
|
private static partial Regex FromPattern();
|
|
}
|
|
|
|
/// <summary>An SMTP server on the loopback interface that keeps every message it receives (no TLS).</summary>
|
|
internal sealed class FakeSmtpServer : IAsyncDisposable
|
|
{
|
|
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
|
|
private readonly CancellationTokenSource _stop = new();
|
|
private readonly Task _loop;
|
|
|
|
public FakeSmtpServer()
|
|
{
|
|
_listener.Start();
|
|
_loop = Task.Run(AcceptAsync);
|
|
}
|
|
|
|
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
|
|
|
|
/// <summary>The messages: sender, recipients, raw content.</summary>
|
|
public ConcurrentQueue<(string From, IReadOnlyList<string> To, byte[] Content)> Messages { get; } = new();
|
|
|
|
/// <summary>When set, RCPT TO is refused with this reply.</summary>
|
|
public string? RejectRecipient { get; set; }
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await _stop.CancelAsync();
|
|
_listener.Stop();
|
|
try
|
|
{
|
|
await _loop;
|
|
}
|
|
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
|
{
|
|
}
|
|
|
|
_stop.Dispose();
|
|
}
|
|
|
|
private async Task AcceptAsync()
|
|
{
|
|
while (!_stop.IsCancellationRequested)
|
|
{
|
|
TcpClient client;
|
|
try
|
|
{
|
|
client = await _listener.AcceptTcpClientAsync(_stop.Token);
|
|
}
|
|
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
|
{
|
|
return;
|
|
}
|
|
|
|
using (client)
|
|
{
|
|
try
|
|
{
|
|
await ServeAsync(client.GetStream());
|
|
}
|
|
catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException)
|
|
{
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task ServeAsync(NetworkStream stream)
|
|
{
|
|
var reader = new LineReader(stream);
|
|
async Task Send(string text) => await stream.WriteAsync(Encoding.ASCII.GetBytes(text + "\r\n"), _stop.Token);
|
|
await Send("220 fake.smtp ESMTP");
|
|
string from = string.Empty;
|
|
var to = new List<string>();
|
|
while (true)
|
|
{
|
|
var line = await reader.LineAsync(_stop.Token);
|
|
if (line is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var upper = line.ToUpperInvariant();
|
|
if (upper.StartsWith("EHLO", StringComparison.Ordinal))
|
|
{
|
|
await Send("250-fake.smtp");
|
|
await Send("250 AUTH PLAIN LOGIN");
|
|
}
|
|
else if (upper.StartsWith("AUTH PLAIN", StringComparison.Ordinal))
|
|
{
|
|
await Send("235 Authenticated");
|
|
}
|
|
else if (upper.StartsWith("MAIL FROM:", StringComparison.Ordinal))
|
|
{
|
|
from = line[10..].Trim('<', '>', ' ');
|
|
to.Clear();
|
|
await Send("250 OK");
|
|
}
|
|
else if (upper.StartsWith("RCPT TO:", StringComparison.Ordinal))
|
|
{
|
|
if (RejectRecipient is not null)
|
|
{
|
|
await Send(RejectRecipient);
|
|
continue;
|
|
}
|
|
|
|
to.Add(line[8..].Trim('<', '>', ' '));
|
|
await Send("250 OK");
|
|
}
|
|
else if (upper == "DATA")
|
|
{
|
|
await Send("354 End data with <CR><LF>.<CR><LF>");
|
|
var data = new StringBuilder();
|
|
while (await reader.LineAsync(_stop.Token) is { } dataLine && dataLine != ".")
|
|
{
|
|
data.Append(dataLine.StartsWith("..", StringComparison.Ordinal) ? dataLine[1..] : dataLine).Append("\r\n");
|
|
}
|
|
|
|
Messages.Enqueue((from, [.. to], Encoding.Latin1.GetBytes(data.ToString())));
|
|
await Send("250 OK queued");
|
|
}
|
|
else if (upper == "QUIT")
|
|
{
|
|
await Send("221 Bye");
|
|
return;
|
|
}
|
|
else
|
|
{
|
|
await Send("502 Not implemented");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>Reads CRLF lines and IMAP literals from a stream.</summary>
|
|
internal sealed class LineReader(Stream stream)
|
|
{
|
|
private readonly byte[] _buffer = new byte[8192];
|
|
private int _start;
|
|
private int _end;
|
|
|
|
public async Task<string?> LineAsync(CancellationToken cancellationToken)
|
|
{
|
|
using var line = new MemoryStream();
|
|
while (true)
|
|
{
|
|
if (_start == _end)
|
|
{
|
|
_start = 0;
|
|
_end = await stream.ReadAsync(_buffer, cancellationToken);
|
|
if (_end == 0)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
var index = Array.IndexOf(_buffer, (byte)'\n', _start, _end - _start);
|
|
if (index < 0)
|
|
{
|
|
line.Write(_buffer, _start, _end - _start);
|
|
_start = _end;
|
|
continue;
|
|
}
|
|
|
|
line.Write(_buffer, _start, index - _start);
|
|
_start = index + 1;
|
|
return Encoding.Latin1.GetString(line.ToArray()).TrimEnd('\r');
|
|
}
|
|
}
|
|
|
|
// A command line with its literals: after each {n} the server says "+" and reads n bytes.
|
|
public async Task<(string? Line, Queue<byte[]> Literals)> CommandAsync(Func<Task> continuation, CancellationToken cancellationToken)
|
|
{
|
|
var text = new StringBuilder();
|
|
var literals = new Queue<byte[]>();
|
|
while (true)
|
|
{
|
|
var line = await LineAsync(cancellationToken);
|
|
if (line is null)
|
|
{
|
|
return (null, literals);
|
|
}
|
|
|
|
text.Append(line);
|
|
var match = Regex.Match(line, @"\{(?<n>[0-9]+)\}$");
|
|
if (!match.Success)
|
|
{
|
|
return (text.ToString(), literals);
|
|
}
|
|
|
|
await continuation();
|
|
var length = int.Parse(match.Groups["n"].Value, CultureInfo.InvariantCulture);
|
|
var bytes = new byte[length];
|
|
var read = 0;
|
|
while (read < length)
|
|
{
|
|
if (_start == _end)
|
|
{
|
|
_start = 0;
|
|
_end = await stream.ReadAsync(_buffer, cancellationToken);
|
|
if (_end == 0)
|
|
{
|
|
return (null, literals);
|
|
}
|
|
}
|
|
|
|
var take = Math.Min(length - read, _end - _start);
|
|
Array.Copy(_buffer, _start, bytes, read, take);
|
|
_start += take;
|
|
read += take;
|
|
}
|
|
|
|
literals.Enqueue(bytes);
|
|
}
|
|
}
|
|
}
|