Files
Khaemhat/src/Khaemhat.Infrastructure/Mail/MimeParser.cs
T
Alby96andClaude Opus 5.5 709bb13532 feat: FatturaPA writer, validator, SDI receipts and transport channels (#74 #75 #76 #77)
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>
2026-11-13 11:51:31 +01:00

542 lines
19 KiB
C#

using System.Globalization;
using System.Text;
namespace Khaemhat.Infrastructure.Mail;
/// <summary>A part of a MIME message: headers and body, or the parts of a multipart, or an enclosed message.</summary>
public sealed class MimePart
{
/// <summary>The headers, names in lower case; repeated headers keep the first value.</summary>
public required IReadOnlyDictionary<string, string> Headers { get; init; }
/// <summary>The media type in lower case, such as <c>multipart/mixed</c> or <c>application/xml</c>.</summary>
public required string MediaType { get; init; }
/// <summary>The parameters of <c>Content-Type</c> (boundary, charset, name), names in lower case.</summary>
public required IReadOnlyDictionary<string, string> TypeParameters { get; init; }
/// <summary>The decoded body (transfer encoding removed); empty for a multipart.</summary>
public byte[] Body { get; init; } = [];
/// <summary>The parts of a multipart.</summary>
public IReadOnlyList<MimePart> Parts { get; init; } = [];
/// <summary>The message enclosed in a <c>message/rfc822</c> part.</summary>
public MimePart? Enclosed { get; init; }
/// <summary>The file name, from <c>Content-Disposition</c> or <c>Content-Type</c>, decoded.</summary>
public string? FileName { get; init; }
/// <summary>A header by name.</summary>
/// <param name="name">The name, any case.</param>
/// <returns>The value, decoded, or <see langword="null"/>.</returns>
public string? Header(string name) => Headers.TryGetValue(name.ToLowerInvariant(), out var value) ? value : null;
/// <summary>The body as text, in its charset (UTF-8 when not declared).</summary>
/// <returns>The text.</returns>
public string Text() => MimeParser.CharsetOf(TypeParameters.TryGetValue("charset", out var charset) ? charset : null).GetString(Body);
/// <summary>Every part with a file name, also inside multiparts and enclosed messages, in order.</summary>
/// <returns>The attachments.</returns>
public IEnumerable<MimePart> Attachments()
{
if (FileName is not null && Parts.Count == 0 && Enclosed is null)
{
yield return this;
}
foreach (var part in Parts)
{
foreach (var attachment in part.Attachments())
{
yield return attachment;
}
}
if (Enclosed is not null)
{
foreach (var attachment in Enclosed.Attachments())
{
yield return attachment;
}
}
}
}
/// <summary>
/// Reads MIME messages (RFC 5322, 2045-2047, 2231) written in house for the PEC channel of the SDI (SPEC §11.9,
/// issue #76): headers with folded lines and encoded words, multiparts at any depth, enclosed messages
/// (<c>message/rfc822</c>, the <c>postacert.eml</c> of a certified mail), bodies in base64, quoted-printable, 7bit and
/// 8bit, file names in <c>filename</c>, <c>filename*</c> and <c>name</c>.
/// </summary>
/// <remarks>Malformed input does not throw: a part whose boundary never closes ends with the message, a broken base64
/// body is decoded as far as it goes. Nesting is limited to 10 levels.</remarks>
public static class MimeParser
{
private const int MaxDepth = 10;
/// <summary>Parses a message.</summary>
/// <param name="message">The raw message.</param>
/// <returns>The root part.</returns>
public static MimePart Parse(byte[] message)
{
ArgumentNullException.ThrowIfNull(message);
return ParsePart(message, 0, message.Length, 0);
}
/// <summary>The encoding of a charset name, UTF-8 when unknown.</summary>
/// <param name="charset">The name.</param>
/// <returns>The encoding.</returns>
public static Encoding CharsetOf(string? charset)
{
switch (charset?.Trim().Trim('"').ToLowerInvariant())
{
case null or "" or "utf-8" or "utf8" or "us-ascii" or "ascii":
return new UTF8Encoding(false);
case "iso-8859-1" or "latin1":
return Encoding.Latin1;
case "windows-1252" or "cp1252":
return CodePagesEncodingProvider.Instance.GetEncoding(1252) ?? Encoding.Latin1;
case "iso-8859-15":
return CodePagesEncodingProvider.Instance.GetEncoding(28605) ?? Encoding.Latin1;
default:
try
{
return Encoding.GetEncoding(charset!.Trim().Trim('"'));
}
catch (ArgumentException)
{
return new UTF8Encoding(false);
}
}
}
/// <summary>Decodes the encoded words of a header (<c>=?utf-8?B?...?=</c>, <c>=?iso-8859-1?Q?...?=</c>).</summary>
/// <param name="value">The raw value.</param>
/// <returns>The text.</returns>
public static string DecodeHeader(string value)
{
ArgumentNullException.ThrowIfNull(value);
var text = new StringBuilder();
var position = 0;
var lastWasEncoded = false;
while (position < value.Length)
{
var start = value.IndexOf("=?", position, StringComparison.Ordinal);
var decoded = start < 0 ? null : TryDecodeWord(value, start, out var end, out var word) ? (end, word) : ((int, string)?)null;
if (decoded is null)
{
var next = start < 0 ? value.Length : start + 2;
text.Append(value, position, next - position);
position = next;
lastWasEncoded = false;
continue;
}
// White space between two encoded words is not part of the text (RFC 2047 §6.2).
var between = value[position..start];
if (!(lastWasEncoded && string.IsNullOrWhiteSpace(between)))
{
text.Append(between);
}
text.Append(decoded.Value.Item2);
position = decoded.Value.Item1;
lastWasEncoded = true;
}
return text.ToString();
}
private static bool TryDecodeWord(string value, int start, out int end, out string word)
{
end = start;
word = string.Empty;
var q1 = value.IndexOf('?', start + 2);
var q2 = q1 < 0 ? -1 : value.IndexOf('?', q1 + 1);
var close = q2 < 0 ? -1 : value.IndexOf("?=", q2 + 1, StringComparison.Ordinal);
if (close < 0)
{
return false;
}
var charset = value[(start + 2)..q1];
var star = charset.IndexOf('*', StringComparison.Ordinal);
if (star >= 0)
{
charset = charset[..star];
}
var mode = value[(q1 + 1)..q2].ToUpperInvariant();
var payload = value[(q2 + 1)..close];
byte[] bytes;
if (mode == "B")
{
bytes = Base64(Encoding.ASCII.GetBytes(payload));
}
else if (mode == "Q")
{
bytes = QuotedPrintable(Encoding.ASCII.GetBytes(payload.Replace('_', ' ')));
}
else
{
return false;
}
word = CharsetOf(charset).GetString(bytes);
end = close + 2;
return true;
}
// --- Parts -------------------------------------------------------------------------------------------------------
private static MimePart ParsePart(byte[] data, int start, int end, int depth)
{
var (headers, bodyStart) = ReadHeaders(data, start, end);
var (mediaType, parameters) = ContentType(headers.TryGetValue("content-type", out var type) ? type : "text/plain");
var disposition = headers.TryGetValue("content-disposition", out var d) ? Parameters(d) : new Dictionary<string, string>(StringComparer.Ordinal);
var fileName = disposition.GetValueOrDefault("filename") ?? parameters.GetValueOrDefault("name");
if (mediaType.StartsWith("multipart/", StringComparison.Ordinal) && parameters.TryGetValue("boundary", out var boundary) && depth < MaxDepth)
{
return new MimePart
{
Headers = headers,
MediaType = mediaType,
TypeParameters = parameters,
Parts = SplitMultipart(data, bodyStart, end, boundary).Select(p => ParsePart(data, p.Start, p.End, depth + 1)).ToList(),
FileName = fileName,
};
}
var body = Decode(data, bodyStart, end, headers.TryGetValue("content-transfer-encoding", out var encoding) ? encoding : null);
if (mediaType == "message/rfc822" && depth < MaxDepth)
{
return new MimePart
{
Headers = headers,
MediaType = mediaType,
TypeParameters = parameters,
Body = body,
Enclosed = ParsePart(body, 0, body.Length, depth + 1),
FileName = fileName,
};
}
return new MimePart { Headers = headers, MediaType = mediaType, TypeParameters = parameters, Body = body, FileName = fileName };
}
private static (Dictionary<string, string> Headers, int BodyStart) ReadHeaders(byte[] data, int start, int end)
{
var headers = new Dictionary<string, string>(StringComparer.Ordinal);
var position = start;
string? name = null;
var value = new StringBuilder();
void Flush()
{
if (name is not null && !headers.ContainsKey(name))
{
headers[name] = DecodeHeader(value.ToString().Trim());
}
name = null;
value.Clear();
}
while (position < end)
{
var lineEnd = IndexOf(data, (byte)'\n', position, end);
var next = lineEnd < 0 ? end : lineEnd + 1;
var line = Encoding.Latin1.GetString(data, position, (lineEnd < 0 ? end : lineEnd) - position).TrimEnd('\r');
position = next;
if (line.Length == 0)
{
Flush();
return (headers, position);
}
if ((line[0] == ' ' || line[0] == '\t') && name is not null)
{
value.Append(' ').Append(line.Trim());
continue;
}
Flush();
var colon = line.IndexOf(':', StringComparison.Ordinal);
if (colon > 0)
{
name = line[..colon].Trim().ToLowerInvariant();
value.Append(line[(colon + 1)..]);
}
}
Flush();
return (headers, end);
}
private static List<(int Start, int End)> SplitMultipart(byte[] data, int start, int end, string boundary)
{
var delimiter = Encoding.ASCII.GetBytes("--" + boundary);
var parts = new List<(int, int)>();
int? partStart = null;
var position = start;
while (position < end)
{
var lineEnd = IndexOf(data, (byte)'\n', position, end);
var contentEnd = lineEnd < 0 ? end : lineEnd;
var next = lineEnd < 0 ? end : lineEnd + 1;
if (StartsWith(data, position, contentEnd, delimiter))
{
var rest = Encoding.ASCII.GetString(data, position + delimiter.Length, contentEnd - position - delimiter.Length).TrimEnd('\r', ' ', '\t');
if (rest is "" or "--")
{
if (partStart is { } open)
{
// The line break before the delimiter belongs to the delimiter.
var close = position;
if (close > open && data[close - 1] == '\n')
{
close--;
}
if (close > open && data[close - 1] == '\r')
{
close--;
}
parts.Add((open, close));
}
if (rest == "--")
{
return parts;
}
partStart = next;
}
}
position = next;
}
if (partStart is { } last && last < end)
{
parts.Add((last, end));
}
return parts;
}
private static byte[] Decode(byte[] data, int start, int end, string? encoding)
{
var slice = data.AsSpan(start, Math.Max(0, end - start)).ToArray();
return encoding?.Trim().ToLowerInvariant() switch
{
"base64" => Base64(slice),
"quoted-printable" => QuotedPrintable(slice),
_ => slice,
};
}
/// <summary>Decodes base64, ignoring line breaks and stopping at the first character that is not base64.</summary>
/// <param name="text">The encoded bytes.</param>
/// <returns>The decoded bytes.</returns>
public static byte[] Base64(byte[] text)
{
ArgumentNullException.ThrowIfNull(text);
var clean = new StringBuilder(text.Length);
foreach (var b in text)
{
var c = (char)b;
if (char.IsAsciiLetterOrDigit(c) || c is '+' or '/' or '=')
{
clean.Append(c);
}
}
var value = clean.ToString().TrimEnd('=');
value = (value.Length % 4) switch
{
2 => value + "==",
3 => value + "=",
1 => value[..^1],
_ => value,
};
var buffer = new byte[value.Length / 4 * 3 + 3];
return Convert.TryFromBase64String(value, buffer, out var written) ? buffer[..written] : [];
}
/// <summary>Decodes quoted-printable (soft line breaks removed).</summary>
/// <param name="text">The encoded bytes.</param>
/// <returns>The decoded bytes.</returns>
public static byte[] QuotedPrintable(byte[] text)
{
ArgumentNullException.ThrowIfNull(text);
using var output = new MemoryStream(text.Length);
for (var i = 0; i < text.Length; i++)
{
var b = text[i];
if (b != '=')
{
output.WriteByte(b);
continue;
}
if (i + 1 < text.Length && text[i + 1] == '\n')
{
i++;
continue;
}
if (i + 2 < text.Length && text[i + 1] == '\r' && text[i + 2] == '\n')
{
i += 2;
continue;
}
if (i + 2 < text.Length && byte.TryParse(Encoding.ASCII.GetString(text, i + 1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value))
{
output.WriteByte(value);
i += 2;
continue;
}
output.WriteByte(b);
}
return output.ToArray();
}
private static (string MediaType, Dictionary<string, string> Parameters) ContentType(string value)
{
var semicolon = value.IndexOf(';', StringComparison.Ordinal);
var mediaType = (semicolon < 0 ? value : value[..semicolon]).Trim().ToLowerInvariant();
return (mediaType.Length == 0 ? "text/plain" : mediaType, Parameters(value));
}
// The parameters after the first ';': name=value, name="quoted value", and RFC 2231 name*=charset''encoded and
// name*0=..., name*1=... continuations, joined.
private static Dictionary<string, string> Parameters(string value)
{
var raw = new List<(string Name, string Value)>();
var position = value.IndexOf(';', StringComparison.Ordinal);
while (position >= 0 && position < value.Length)
{
position++;
var equals = value.IndexOf('=', position);
if (equals < 0)
{
break;
}
var name = value[position..equals].Trim().ToLowerInvariant();
position = equals + 1;
while (position < value.Length && value[position] == ' ')
{
position++;
}
string parameter;
if (position < value.Length && value[position] == '"')
{
var close = position + 1;
var quoted = new StringBuilder();
while (close < value.Length && value[close] != '"')
{
if (value[close] == '\\' && close + 1 < value.Length)
{
close++;
}
quoted.Append(value[close]);
close++;
}
parameter = quoted.ToString();
position = value.IndexOf(';', Math.Min(close + 1, value.Length));
}
else
{
var semicolon = value.IndexOf(';', position);
parameter = (semicolon < 0 ? value[position..] : value[position..semicolon]).Trim();
position = semicolon;
}
raw.Add((name, parameter));
}
var result = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var group in raw.GroupBy(p => p.Name.Split('*')[0]))
{
var extended = group.Where(p => p.Name.Contains('*', StringComparison.Ordinal)).ToList();
if (extended.Count == 0)
{
result[group.Key] = DecodeHeader(group.First().Value);
continue;
}
var ordered = extended
.OrderBy(p => int.TryParse(p.Name.Split('*').ElementAtOrDefault(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : 0)
.ToList();
var charset = "utf-8";
var bytes = new List<byte>();
foreach (var (name, part) in ordered)
{
var text = part;
if (name.EndsWith('*'))
{
var first = text.IndexOf('\'', StringComparison.Ordinal);
var second = first < 0 ? -1 : text.IndexOf('\'', first + 1);
if (second > first)
{
if (first > 0)
{
charset = text[..first];
}
text = text[(second + 1)..];
}
bytes.AddRange(PercentDecode(text));
}
else
{
bytes.AddRange(Encoding.UTF8.GetBytes(text));
}
}
result[group.Key] = CharsetOf(charset).GetString(bytes.ToArray());
}
return result;
}
private static byte[] PercentDecode(string text)
{
var output = new List<byte>(text.Length);
for (var i = 0; i < text.Length; i++)
{
if (text[i] == '%' && i + 2 < text.Length && byte.TryParse(text.AsSpan(i + 1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value))
{
output.Add(value);
i += 2;
}
else
{
output.AddRange(Encoding.UTF8.GetBytes(text[i].ToString()));
}
}
return [.. output];
}
private static int IndexOf(byte[] data, byte value, int start, int end)
{
var index = Array.IndexOf(data, value, start, end - start);
return index;
}
private static bool StartsWith(byte[] data, int start, int end, byte[] prefix) =>
end - start >= prefix.Length && data.AsSpan(start, prefix.Length).SequenceEqual(prefix);
}