using System.Globalization;
using System.Text;
namespace Khaemhat.Infrastructure.Mail;
/// A part of a MIME message: headers and body, or the parts of a multipart, or an enclosed message.
public sealed class MimePart
{
/// The headers, names in lower case; repeated headers keep the first value.
public required IReadOnlyDictionary Headers { get; init; }
/// The media type in lower case, such as multipart/mixed or application/xml.
public required string MediaType { get; init; }
/// The parameters of Content-Type (boundary, charset, name), names in lower case.
public required IReadOnlyDictionary TypeParameters { get; init; }
/// The decoded body (transfer encoding removed); empty for a multipart.
public byte[] Body { get; init; } = [];
/// The parts of a multipart.
public IReadOnlyList Parts { get; init; } = [];
/// The message enclosed in a message/rfc822 part.
public MimePart? Enclosed { get; init; }
/// The file name, from Content-Disposition or Content-Type, decoded.
public string? FileName { get; init; }
/// A header by name.
/// The name, any case.
/// The value, decoded, or .
public string? Header(string name) => Headers.TryGetValue(name.ToLowerInvariant(), out var value) ? value : null;
/// The body as text, in its charset (UTF-8 when not declared).
/// The text.
public string Text() => MimeParser.CharsetOf(TypeParameters.TryGetValue("charset", out var charset) ? charset : null).GetString(Body);
/// Every part with a file name, also inside multiparts and enclosed messages, in order.
/// The attachments.
public IEnumerable 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;
}
}
}
}
///
/// 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
/// (message/rfc822, the postacert.eml of a certified mail), bodies in base64, quoted-printable, 7bit and
/// 8bit, file names in filename, filename* and name.
///
/// 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.
public static class MimeParser
{
private const int MaxDepth = 10;
/// Parses a message.
/// The raw message.
/// The root part.
public static MimePart Parse(byte[] message)
{
ArgumentNullException.ThrowIfNull(message);
return ParsePart(message, 0, message.Length, 0);
}
/// The encoding of a charset name, UTF-8 when unknown.
/// The name.
/// The encoding.
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);
}
}
}
/// Decodes the encoded words of a header (=?utf-8?B?...?=, =?iso-8859-1?Q?...?=).
/// The raw value.
/// The text.
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(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 Headers, int BodyStart) ReadHeaders(byte[] data, int start, int end)
{
var headers = new Dictionary(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,
};
}
/// Decodes base64, ignoring line breaks and stopping at the first character that is not base64.
/// The encoded bytes.
/// The decoded bytes.
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] : [];
}
/// Decodes quoted-printable (soft line breaks removed).
/// The encoded bytes.
/// The decoded bytes.
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 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 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(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();
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(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);
}